基本概念

    • store state 当state变化时需要返回全新的对象,而不是修改传入的参数
    • action
    • reducer

      1. let store = createStore(counter);
      2. store.subscribe(() => console.log(store.getState()) ); // 更新订阅
      3. store.dispatch({type: 'INCREMENT'});

      单项数据流

    • dispatch(action)

    • reducer -> newState
    • subscribe 触发通知

    image.png
    react-redux

    • connect
    • connect
    • mapStateToProps、mapDispatchToProps

      1. <Provider store={store}></Provider>
      2. let childComp = ({ dispatch }) => {...}
      3. childComp = connect()(childComp) // connect高阶组件, 将dispatch作为props注入
      4. dispatch(addTodo(...)) // 函数返回action, 对象形式

      异步action
      同步返回对象, 异步返回函数

    • redux-thunk

    • redux-promise
    • redux-saga

    const store = createStore(rootReducer, applyMidddleware(thunk))

    1. addTodoAsync = text => {
    2. return (dispatch) => {
    3. fetch(url).then(res => {
    4. dispatch(addTodo(res.text))
    5. })
    6. }
    7. }

    中间件

    1. import createLogger from 'redux-logger';
    2. import thunk from 'redux-thunk';
    3. const logger = createLogger();
    4. const store = createStore(reducer, applyMiddleware(thunk, logger));
    5. // 增加logger
    6. let next = store.dispatch;
    7. store.dispatch = function dispatchAndLog(action) {
    8. console.log('dispatching', action);
    9. next(action);
    10. console.log('next state', store.getState());
    11. }