5.createContext、useContext+useReducer实现react-redux

reducer模块化

createContext+useReducer实现react-redux

import React, { useReducer,useContext,createContext } from 'react'
import { ADD_NUM } from './store/actionTypes'
import { numRreduce } from './store/reducer'

创建上下文空间

const NumContext=createContext()

子组件

改为consumer写法===============

function Sub() {
    // const { state} =useContext(NumContext)
    // return <h2>{ state.num}</h2>
      return (
        <NumContext.Consumer>
        //解构出来state
            {({ state}) => {
                return <h2>{ state.num}</h2>
            }}
        </NumContext.Consumer>
    )
}

按钮子组件

改为consumer写法===============

function Btn() {
    // const { dispatch} =useContext(NumContext)
    // return <button onClick={() => dispatch({type:ADD_NUM,value:1})}>增加</button>
    <NumContext.Consumer>
    	//解构出来dispatch
        {({ dispatch}) => {
            return (<button onClick={() => dispatch({type:ADD_NUM,value:1})}>增加</button> )
        }}
    </NumContext.Consumer>
}

语法:const [state,dispatch] = useReducer(定义的reducer, state的初始值)

export default function App() {
    // const [num,setNum]=useState(0)
    
    const [state,dispatch] = useReducer(numRreduce, {num:0})
    console.log('state',state);
    return (
        <div>
            <NumContext.Provider value={{ state, dispatch }}>
                {/* 使用dispatch调用 */}
                {/* 向上下文空间传递参数 */}
                <Sub/>
                <Btn/>
            </NumContext.Provider>
        </div>
    )
}

store/reducer.js

/*
 * @Description:d\导出每一个reducer
 * @Author: cqj
 * @Date: 2021-12-02 15:15:16
 * @LastEditTime: 2021-12-02 15:19:11
 * @LastEditors: cqj
 * @Reference:
 */
import { ADD_NUM } from './actionTypes'
//定义一个关于num的reducer
export const numRreduce = (state, action) => {
    let newState = JSON.parse(JSON.stringify(state))
    switch (action.type) {
        case ADD_NUM:
            newState.num += action.value
            break
        default:
            break;
    }
    return newState
}

// function msgRreduce() { }

store/actionTypes.js

/*
 * @Description:
 * @Author: cqj
 * @Date: 2021-12-02 15:18:35
 * @LastEditTime: 2021-12-02 15:18:35
 * @LastEditors: cqj
 * @Reference:
 */
export const ADD_NUM = 'addNum'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值