基本
import { createStore } from 'redux';
// reducer 是个函数,参数为 state(设置初始值)和 action,返回值为新的 state
const reducer = (state = 0, action){
switch (action.type) {
case 'add':
return state + action.payload;
case 'delete':
return state - action.payload;
default:
return state;
}
}
// 生成 store
let store = createStore(reducer);
// 获取状态
store.getState();
const action1 = {
type: 'add',
payload: 2,
}
// action 生成函数
const createAction = (val) => ({
type: 'add',
payload: val,
})
// 使用 store.dispatch(action)来分发 action
store.dispatch(action1);
store.dispatch(createAction(2));
//store 还可以订阅监听器
// 当我们 dispatch 了 action 后,会触发函数
store.subscribe(() => {
console.log('change state');
})