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>
    )
}

posted @ 2020-11-25 09:17  yaogengzhu  阅读(218)  评论(0编辑  收藏  举报