React状态管理库 -- Redux篇

如何实现一个redux?

确切来说应该是js状态管理库, redux现在常用redux-toolkit,以后有机会总结。

  1. 什么是reducer?

    reducer 是一个纯函数,传入旧的state和action,返回新的state。(可以类比js reduce函数)。

JavaScript 复制代码
   const reducer =  (previousState, action) => newState
  1. Redux基本概念
  • React Component
  • Action Creators
  • Store
  • Reducers
  1. Redux 基本使用
JavaScript 复制代码
export default function ReduxPage(){
    const [state, setState] = useState(store.getState().count);
    const add = () => {
        store.dispatch({type: 'ADD'})
    }
    const minus = () => {
        store.dispatch({type: 'Minus'})
    }
    useEffect(() => {
        const unsubscribe = store.subscribe(() => {
            setState(store.getState().count);
        });
        return () => unsubscribe();
    }, []);
    return(
        <div>
            <h3>ReduxPage</h3>
            <p>{state}</p>
            <button onClick={add}>add</button>
        </div>
    )
}
JavaScript 复制代码
function countReducer(state = 0, action){
    switch(action.type){
        case "ADD":
            return state + 1
        case "Minus":
            return state - 1
        default:
            return state
    }
}
export const store = createStore(countReducer)
  1. Redux基本实现

createStore -- 发布订阅模式

接收什么?

目前是一个reducer。(还可以加入中间件)

返回什么?

{getState,dispatch,subscribe}三个方法。

JavaScript 复制代码
export default function createStore (reducer) {
    let currentState
    let currentListeners = []
    function getState(){
        return currentState
    }
    function dispatch(action){
        currentState = reducer(currentState,action)
        currentListeners.forEach(listener=>{
            listener()
        })
    }
    function subscribe(listener){
        currentListeners.push(listener)
        return () => {
            const index = currentListeners.indexOf(listener)
            currentListeners.splice(index,1)
        }
    }
    dispatch({type:'ADADAD'})
    return {getState,dispatch,subscribe}
}

思考: 为什么要dispatch({type:'ADADAD'}),其实是拿到初始状态(本例子中的state = 0),触发default:return state,不要忘记加。

  1. rudux中间件 想要增强redux的功能,如异步(redux-thunk),日志打印(redux-logger)等,可以使用中间件来增强一般的redux,以后有机会总结一下如何实现。

  2. 管理多个reducer

在一个项目中,可能会有很多不同的状态需要管理,也就是有很多reducer, 那么我们需要将多个reducer合并成一个reducer。

怎么使用呢?

JavaScript 复制代码
export const store = createStore(
    combineReducers({count:countReducer,和其他reducer}),
    applyMiddleware(thunk,logger)) //这个是中间件,暂时可以不管它

如何实现一个combineReducer?

先考虑接受什么参数? -- 一个对象,包含所有reducer。

返回什么? 一个总的reducer。

JavaScript 复制代码
export default function combineReducers(reducers) {
  return function combination(state = {}, action) {
    let nextState = {};
    let hasChanged = false;

    for (let key in reducers) {
      const reducer = reducers[key];
      nextState[key] = reducer(state[key], action);
      hasChanged = hasChanged || nextState[key] !== state[key];
    }

    hasChanged =
      hasChanged || Object.keys(reducers).length !== Object.keys(state).length;

    return hasChanged ? nextState : state; //优化一下,判断一下当前状态值到底变了没有,不改变就返回老的。
  };
}
相关推荐
deli00720 小时前
手机拍灯为什么有一条条黑纹?PWM 240Hz 实测
前端
wangruofeng1 天前
AI Models 1.1.0 发布,查大模型价格、对比模型和找 API 地址
前端·aigc·ai编程
wangruofeng1 天前
给前端开发者的 100 个设计参考网站
前端·设计
星栈1 天前
视频即代码,Remotion 能做什么、不能做什么
前端·音视频开发
广州华水科技1 天前
单北斗GNSS位移监测系统的应用与技术解析
前端
用户47949283569151 天前
从一句话或代码仓到可交互 HTML:开源 Agent 画图技能 Archify v3.2 实测与选型边界
前端·后端·面试
风骏时光牛马1 天前
生成一个AI多模态标题,仅输出一条标题,无额外文字、问句、备选、配图、文案等任何附加内容,不需要其他的任务服务 只要标题。
前端
wangruofeng1 天前
从 GIF 到 AVIF:网页图片格式演进与 2026 年选型指南
前端·架构
清晨Coding1 天前
为什么用 React Developer Tools 查看组件树这么乱?
前端·react.js
鶴哥只手遮天1 天前
《Electron 45.2.3 内核解剖》第 4 章 补丁体系:380 个补丁改了什么
前端·electron