react中useReducer使用

在react项目中,我们可以使用redux状态全局化,在开发中只需要维护单一的数据源即可解决多组件数据使用,现在我们多使用的是hook来开发,react官方中提供了useReducer + Provider来实现类似的功能;

初始化Store.ts

import { createContext } from 'react'

export interface IStateProps {
    name: string
}
export interface IActionProps {
    type: string
    payload?: any
}

export const state = {
    name: 'xhh'
}

export const Reducer = (state: IStateProps, action: IActionProps) => {
  switch (action.type) {
    case 'CHANGE_NAME':
      return { ...state, name: action.payload }
    default:
      throw new Error('reducer没有当前type方法')
  }
}

// eslint-disable-next-line @typescript-eslint/no-empty-function
export const context = createContext({ state, dispatch: (obj: IActionProps) => {} })

export const Provider = context.Provider
export const Consumer = context.Consumer

父组件使用provider

// 引入
import { Reducer, state as initalState, Provider } from './Store'
const Parent:FC<any> = (props) => {
  const [state, dispatch] = useReducer(Reducer, initalState)
  return <Provider value={{state, dispatch}}>
                Index
            </Provider>
}

子组件使用context

import React, { useContext } from 'react'
import { context } from './Store'
const Child:FC<any> = (props) => {
  const { state, dispatch } = useContext(context)
  return <>
    {state.name}
    <button onClick={() => dispatch({type: 'CHANGE_NAME‘, payload: 'hello xhh'})}>change</button>
    </>
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容