原文链接Redux 入门教程(一):基本用法,本文是看完之后的一个简单总结
redux的一些概念
store,state,action, dispatch,reducer
- store: 存储数据的地方,整个应该只有一个 store
- state: 某个具体的数据,跟 view 一一对应
- action:是一个对象,改变 state 的唯一方式,通过 action,会运送数据到 store
const action = {
type: 'ADD_TODO', // type属性表示action名称
payload: 'Learn Redux',
};
Action Creator: 一个函数,用来生成 action
- dispatch:一个函数,view 发出 action 的唯一方法,接受 action 对象作为参数,将它发出去。
import { createStore } from 'redux';
const store = createStore(fn);
store.dispatch({
type: 'ADD_TODO',
payload: 'Learn Redux',
});
-
reducer:store 接受到 action,通过计算给出新的 state,这个计算过程称为 reducer
是一个纯函数,接受当前 state 和 action 为参数,返回新的 stateconst reducer = function (state, action) { // ... return new_state; };
纯函数
- 不得改写参数
- 不用调用系统 I/O 的 api
- 不用调用 Date.now(), Math.random()等不纯的方法,因为每次返回结果不一样
// State 是一个对象
function reducer(state, action) {
return Object.assign({}, state, { thingToChange });
// 或者
return { ...state, ...newState };
}
// State 是一个数组
function reducer(state, action) {
return [...state, newItem];
}
store.dispatch 方法会自动触发 reducer 的自动执行。
在生成 store 的时候将 reducer 传进入,这个时候每当 dispatch 发送一个新的 action,就会自动调用 reducer,生成新的 state
import { createStore } from 'redux';
const store = createStore(reducer);
createStore 的简单实现
const createStore = (reducer) => {
let state;
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 };
};
redux 工作流程
- 通过 dispatch 触发 action
store.dispatch(action);
- store 自动调用 reducer,reducer 接受 state 和 action,通过计算返回新的 state
let nextState = todoApp(previousState, action);
- state 一旦变化,会触发监听函数
// 设置监听函数
store.subscribe(listener);
function listerner() {
let newState = store.getState();
component.setState(newState);
}
react 的 useReducer
const [state, dispatch] = useReducer(reducer, initialArg, init);
接受一个形如(state, action) => newState 的 reducer,返回当前 state 及其配套的 dispatch
网友评论