useReducer与useContext组合实现跨组件的状态管理

useReducer 参数 1:reducer 函数,参数2:state的初始值。reducer函数接受两个参数 state、 action 。返回一个新的state 和 dispath,dispatch用来发布事件更新 state。

下面的例子中,父组件定义state、dispatch,通过Context与子组件公用state、dispatch。从而实现跨组件的状态管理。

index.react.js

import React, { useReducer } from "react";
import reducer from "../reducer";
import SelectedList from "./selectedList/index.react";
function ChooseMemeber ({listData}) {
    const MemeberContext = createContext();
    const [state, dispatch] = useReducer(reducer, {
        selectedList: [],
        isShow: false
    });
    const {selectedList, isShow} = state;
    useEffect(() => {
        dispatch({ type: 'saveSelectedList', payload: [...listData] });
    }, [listData])

    return (
        <MemeberContext.Provider value={{ state, dispatch }}>//公用参数
            <SelectedList />
        </MemeberContext.Provider>
    )
}

reducer.js

function reducer(state, action) {
    switch (action.type) {
        case 'saveSelectedList':
            return {...state, selectedList: action.payload}
        case 'isShow':
            return {...state, isShow: action.payload}
        default:
            return state
    }
}
export default reducer

selectedList/index.react

import React, { useContext } from "react";
import { MemeberContext } from "../../index.react";
function SelectedList () {
    const memberCtx = useContext(MemeberContext);
    const { state: {selectedList}, dispatch } = memberCtx;
       const selectItem = (info, key) => {
        //todo selectedList
        dispatch({type: 'saveSelectedList', payload: [...selectedList]})
   }
   return (
        <div>
            {selectedList.map(data => {
                return <div>data.name</div>
            })}
        </div>
    )
}
export default SelectedList

useReducer和redux

useReducer 和 redux 十分类似。但是useReducer不是一个整合的store,redux是。
userReducer中的dispatch是各自独立的,不像redux,是共同的。

useReducer和useState

如果你的state被多个component引用,请使用useReducer。

posted @ 2022-03-05 14:48  梁涛999  阅读(241)  评论(0编辑  收藏  举报