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'