Redux入门
安装
npm install --save redux
react绑定库和开发者工具
npm install --save react-redux npm install --save-dev redux-devtools
几个概念:
- 所有的state以一个对象树的形式存储在单一的store中
- 唯一改变state的方法就是触发action
- reducer为一个纯函数, 描述如何将一个state转变为下一个state,需要对reducer进行拆分
- Redux不像Flux,没有Dispatcher且不支持多个store;
如何创建Redux store存放应用状态,api是 { subscribe, dispatch, getState };
let store = createStore(reducer)
可以订阅更新,也可以将事件绑定到视图层
store.subscribe(() => {console.log( store.getState() );})
state具体是怎么样的?
{ todos: [{text: 'Eat food',completed: true}, {text: 'Exercise',completed: false}],visibilityFilter: 'SHOW_COMPLETED' }
改变内部state的方法是dispatch一个action,action 可以序列化保存,以便回放
store.dispatch({ //action描述当前发生的事,为一个对象,type是必须属性type: 'INCREMENT',payload: 'Learn Redux'})
reducer把action,state串起来,用来管理整个应用的state;
function visibilityFilter(state = 'SHOW_ALL', action) {if (action.type === 'SET_VISIBILITY_FILTER') {return action.filter;} else {return state;}}function todos(state = [], action) {switch (action.type) {case 'ADD_TODO':return state.concat([{ text: action.text, completed: false }]);case 'TOGGLE_TODO':return state.map((todo, index) =>action.index === index ? { text: todo.text, completed: !todo.completed } : todo)default: return state;}}
function todoApp(state = {}, action) {return {todos: todos(state.todos, action),visibilityFilter: visibilityFilter(state.visibilityFilter, action)};}
Redux的三大原则
- 单一数据源
- state是只读的,只能通过触发action
- 使用纯函数来执行修改
import { combineReducers, createStore } from 'redux'let reducer = combineReducers({ visibilityFilter, todos })let store = createStore(reducer)
工作流程
- 用户发出action store.dispatch(action);
-
Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。
- State 一旦有变化,Store 就会调用监听函数。
store.subscribe(listener);
fff
如何成为一个有思想的程序员?博客未尝不是一个好方法

浙公网安备 33010602011771号