Skip to main content

状态管理•React Redux

Redux 是 JavaScript 应用程序的可预测状态容器。

React Redux 是 Redux 的官方 React UI 绑定层,它使 React 组件能够从 Redux 存储中读取数据,并且可以向存储派发动作来更新状态。

当我们使用 Redux 后,应用程序状态变成这样。

Redux

简单的 Redux 模拟实现

const createStore = (reducer, initialState = undefined) => {
let state = initialState;
let listeners = [];

const getState = () => state;

const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};

const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
};

dispatch({});

return { getState, dispatch, subscribe };
};

function reducer(state = 0, action) {
const { type, payload } = action;
switch (type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
case 'INCREMENT_BY':
return state + payload.count
default:
return state
}
};
const store = createStore(reducer);

store.subscribe(() => {
console.log('State updated:', store.getState());
});

store.dispatch({ type: 'INCREMENT' }); // state的值是1

store.dispatch({
type: 'INCREMENT_BY',
payload: {
count: 2
}
}); // state的值是3
  • store:状态的容器,包含了应用程序的全部状态
  • action:描述状态变化的对象,type 属性表示动作类型
  • reducer:纯函数,接收旧状态和动作,返回新状态
  • subscribe:注册监听器函数,用于订阅状态的变化
  • dispatch:派发任务函数,用于触发状态的变化