安装
安装稳定版:
npm install --save redux
index.js:
const redux = require('redux');
// 定义一个状态
let initialState = {
count: 0
};
// 利用 store 来保存状态(state)
const store = redux.createStore(reducer);
// 利用 action 来修改状态
const addAction = {type: 'ADD_COUNT', num: 1};
const subAction = {type: 'SUB_COUNT', num: -1};
// 利用 reducer 将 store 和 action 串联起来
function reducer(state = initialState, action) {
switch (action.type) {
case 'ADD_COUNT':
return {count: state.count + action.num};
case 'SUB_COUNT':
return {count: state.count - action.num};
default:
return state;
}
}
监听状态的改变
store.subscribe(() => {
console.log(store.getState());
});
从 Store 中获取存储的状态
console.log(store.getState());
修改 Store 中存储的状态
store.dispatch(addAction);