安装
yarn add redux
使用
Reducer
- 一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
是一个纯函数。也就是说,只要是同样的输入,必定得到同样的输出。因此 Reducer 函数里面不能改变 State,必须返回一个全新的对象,
const reducer = function (state, action) {// ...return new_state;};
createStore
创建一个 store,接受一个函数 Reducer
import { createStore } from 'redux';const store = createStore(Reducer);
getState
获取 store 里的数据
store.getState()
action
Action 是一个对象。其中的
type属性是必须的,表示 Action 的名称。其他属性可以自由设置,社区有一个规范 可以参考。const action = {type: 'ADD_TODO',payload: 'Learn Redux'};
Action Creator
View 要发送多少种消息,就会有多少种 Action。如果都手写,会很麻烦。可以定义一个函数来生成 Action,这个函数就叫 Action Creator。
const ADD_TODO = '添加 TODO';function addTodo(text) {return {type: ADD_TODO,text}}const action = addTodo('Learn Redux');
dispatch
store.dispatch()是 View 发出 Action 的唯一方法。import { createStore } from 'redux';const store = createStore(fn);store.dispatch({type: 'ADD_TODO',payload: 'Learn Redux'});
subscribe
Store 允许使用
store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。import { createStore } from 'redux';const store = createStore(reducer);store.subscribe(listener);
只要把 View 的更新函数(对于 React 项目,就是组件的render方法或setState方法)放入listen,就会实现 View 的自动渲染。
store.subscribe 方法返回一个函数,调用这个函数就可以解除监听
let unsubscribe = store.subscribe(() =>console.log(store.getState()));unsubscribe();
总结
1. 创建一个 reducer,两个参数 state action
2. 将 reducer 作为参数创建一个 store
2. dispatch 一个 action 对象,reducer 会接受 action 返回一个新 state
2. 监听 state,su bscribe 订阅一个回调,state 变化时触发
问题
隔代组件间传递数据需要层层传递,使用 react-reducer 解决
