react中React.createContext 结合 useReducer 简单的demo
import React, { useReducer } from 'react'
// 定义初始化的变量
interface IFormType {
name: string
age: number
}
interface Action {
type: 'set' | 'update',
value: IFormType
}
const formData = (): IFormType => {
return {
name: 'zs',
age: 12
}
}
const reducer = (state: IFormType, action: Action): IFormType => {
switch (action.type) {
case 'set':
return action.value
case 'update':
return action.value
}
}
const AppContext = React.createContext<IFormType>(formData())
export const Demo: React.FC = () => {
// 使用useReducer
const [state, dispatch] = useReducer(reducer, formData())
return (
<div>
<AppContext.Provider value={state}>
<button onClick={() => {
dispatch({
type: 'update',
value: {
...state,
'age': 20
}
})
}}>改变age</button>
<Son />
<SonOne />
</AppContext.Provider>
</div>
)
}
const Son = () => {
const { name, age } = React.useContext(AppContext)
return (
<div>
<div>{age}</div>
<div>{name}</div>
</div>
)
}
const SonOne = () => {
const { name, age } = React.useContext(AppContext)
return (
<div>
<div>{age}</div>
<div>{name}</div>
</div>
)
}
一份帮助文档,无论多么仔细,都不会帮助主人多敲一行代码!