
其中核心模块式action、store、reducer,一般情况下先写reducer的逻辑,相当于MVC中的控制器controller,实现对数据的操作、修改,但凡涉及到数据的改变,都需要reducer介入。
reducer实际上是一个普通函数,有两个参数state、action,state表示之前仓库中的状态(数据),action表示要做什么的对象

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
function reducer(state, action) { if (action.type === 'increase') { return state + 1; } else if (action.type === 'decrease') { return state - 1; } else { return state; } }
|
reducer一般由自己编写逻辑,store可以通过Redux中的createStore()方法创建
1 2 3 4 5 6
| const store = createStore(reducer, state); const action = { type: 'increase' };
store.dispatch(action);
store.getState()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import { createStore } from 'redux';
function reducer(state, action) { if (action.type === 'increase') { return state + 1; } else if (action.type === 'decrease') { return state - 1; } else { return state; } }
const store = createStore(reducer, 10); const action = { type: 'increase' }; console.log('old store:', store.getState());
store.dispatch(action); console.log('new store:', store.getState());
|