在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>
</>
}