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

 功能:

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

目录:

App.js:

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

function App() {
  return (
    <ContextReducer />
  );
}

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 (
    <GlobalContext.Provider value={{
      state,
      dispatch
    }}>
      <Child1 GlobalContext={GlobalContext} />
      <Child2 GlobalContext={GlobalContext} />
      <Child3 GlobalContext={GlobalContext} />
    </GlobalContext.Provider>
  )
}

Child1(子组件):

import React, {useContext} from 'react'

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

  return (
    <div>
      Child1
      <button onClick={() => {
        dispatch({type: 'changeA'})
      }}>改变a</button>
      <button onClick={() => {
        dispatch({type: 'changeB'})
      }}>改变b</button>
      <p>
        {state.num}
      </p>
    </div>
  )
}

export default Child1

Child2(子组件):

import React, {useContext} from 'react'

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

  return (
    <div>
      ChildA
      <p>
        {state.a}
      </p>
    </div>
  )
}

export default Child1

Child3(子组件):

import React, {useContext} from 'react'

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

  return (
    <div>
      ChildB
      <p>
        {state.b}
      </p>
    </div>
  )
}

export default Child1

运行结果:

初始状态:

 点击改变a按钮:

 点击改变b按钮:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值