React hooks useContext、useReducer结合使用实现数据状态共享

 功能:

点击Child1中的两个按钮,改变Child2、Child3的数据。

目录:

React hooks useContext、useReducer结合使用实现数据状态共享_第1张图片

App.js:

import './App.css';
import ContextReducer from './contextReducer/ContextReducer'

function App() {
  return (
    
  );
}

export default App;

 ContextReducer.js(父组件):

import React, { useReducer } from 'react'
import Child1 from './children/Child1'
import Child2 from './children/Child2'
import Child3 from './children/Child3'

const reducers = (prevState, action) => {
  console.log(prevState, action);
  let newState = { ...prevState }
  switch (action.type) {
    case 'changeA':
      newState.a = 6
      return newState
    case 'changeB':
      newState.b = 7
      return newState
    default:
      return newState
  }
}

const initialStates = {
  a: 0,
  b: 1
}

export default function ContextReducer() {
  const GlobalContext = React.createContext();
  const [state, dispatch] = useReducer(reducers, initialStates);
  return (
    
      
      
      
    
  )
}

Child1(子组件):

import React, {useContext} from 'react'

const Child1 = (props) => {
  const {GlobalContext} = props;
  console.log(GlobalContext);
  const {state, dispatch} = useContext(GlobalContext)

  return (
    
Child1

{state.num}

) } export default Child1

Child2(子组件):

import React, {useContext} from 'react'

const Child1 = (props) => {
  const {GlobalContext} = props;
  const {state, dispatch} = useContext(GlobalContext)

  return (
    
ChildA

{state.a}

) } export default Child1

Child3(子组件):

import React, {useContext} from 'react'

const Child1 = (props) => {
  const {GlobalContext} = props;
  const {state, dispatch} = useContext(GlobalContext)

  return (
    
ChildB

{state.b}

) } export default Child1

运行结果:

初始状态:

React hooks useContext、useReducer结合使用实现数据状态共享_第2张图片

 点击改变a按钮:

React hooks useContext、useReducer结合使用实现数据状态共享_第3张图片

 点击改变b按钮:

React hooks useContext、useReducer结合使用实现数据状态共享_第4张图片

 

你可能感兴趣的:(ant,design,-,react,react.js,前端,hooks,useReducer,useContext)