基本概念
- store state 当state变化时需要返回全新的对象,而不是修改传入的参数
- action
reducer
let store = createStore(counter);
store.subscribe(() => console.log(store.getState()) ); // 更新订阅
store.dispatch({type: 'INCREMENT'});
单项数据流
dispatch(action)
- reducer -> newState
- subscribe 触发通知
react-redux
connect - connect
mapStateToProps、mapDispatchToProps
<Provider store={store}></Provider>
let childComp = ({ dispatch }) => {...}
childComp = connect()(childComp) // connect高阶组件, 将dispatch作为props注入
dispatch(addTodo(...)) // 函数返回action, 对象形式
异步action
同步返回对象, 异步返回函数redux-thunk
- redux-promise
- redux-saga
const store = createStore(rootReducer, applyMidddleware(thunk))
addTodoAsync = text => {
return (dispatch) => {
fetch(url).then(res => {
dispatch(addTodo(res.text))
})
}
}
中间件
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
const logger = createLogger();
const store = createStore(reducer, applyMiddleware(thunk, logger));
// 增加logger
let next = store.dispatch;
store.dispatch = function dispatchAndLog(action) {
console.log('dispatching', action);
next(action);
console.log('next state', store.getState());
}