zoukankan      html  css  js  c++  java
  • 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>
        )
    }
    
    
  • 相关阅读:
    连通分量板子
    2017年7月17日
    强连通缩点— HDU1827
    马拉车代码
    表达式求值
    Gym-100883F、Gym-101095B状态压缩小结
    矩阵快速幂小结-Hdu2604
    3月27日
    简单移动端自适应轮播图
    上了热搜榜前端工程师面试内幕
  • 原文地址:https://www.cnblogs.com/yaogengzhu/p/14034018.html
Copyright © 2011-2022 走看看