react useReducer加useContext 实现redux全局状态共享及修改

直接代码

创建context文件

import React from react;
interface context {
          
   
  state: any,
  dispatch: any,
}
const Context = React.createContext<context>(null)
export default Context

根组件hooks

import React, {
          
    useMemo, useReducer } from react;
import Context from @/context/index

const reduxData = {
          
   
  name: ,
  pwd: ,
  lan: ch
}
function changeRedux(state, data) {
          
   
  const [key, val] = data
  state[key] = val
  return {
          
   
    ...state
  }
}


export default function MyApp({
          
    Component, pageProps }) {
          
   
  const [state, dispatch] = useReducer(changeRedux, reduxData)
  return (
    <Context.Provider value={
          
   {
          
   
      state,
      dispatch
    }}>
      <Component {
          
   ...pageProps} />
    </Context.Provider>
  )
}

使用(所有组件都可以用)

import React, {
          
    useContext } from react;
import Context from @/context/index
import {
          
    Button } from antd;

const detail = () => {
          
   
  const  {
          
    state, dispatch }  = useContext(Context)
  return (
    <div>
      <Button type="primary" onClick={
          
   () => {
          
   
        dispatch([name,zlaz])
      }}>改变名字</Button>
      <div>name: {
          
   state.name}</div>
    </div>
  )
}

export default detail;
当点击按钮时 全局组件的状态的name更新为zlaz
经验分享 程序员 微信小程序 职场和发展