• 和 vuex 作用相同,但是比 Vuex 学习成本高

    基本概念

    ```jsx import { createStore } from ‘redux’;

function counter(state = 0, action) { switch (action.type) { case ‘INCREMENT’: return state + 1; case ‘DECREMENT’: return state - 1; default: return state; } }

let store = createStore(counter);

store.subscribe(() => console.log(store.getState))

store.dispatch({ type: ‘INCREMENT’ })

  1. <a name="vlTns"></a>
  2. # 单向数据流概述
  3. 1. dispatch(action)
  4. 1. reducer -> newState
  5. 1. subscribe 触发通知
  6. <a name="An2Ot"></a>
  7. # react-redux
  8. - <Provider>
  9. - connect
  10. - mapStateToProps mapDispatchToProps
  11. <a name="gG2mx"></a>
  12. # 异步 action
  13. ```jsx
  14. export const addTodo = text => {
  15. // 返回 action 对象
  16. return {
  17. type: 'ADD_TODO',
  18. id: nextTodoID++,
  19. text
  20. }
  21. }
  1. import { createStore, applyMiddleware} from 'redux';
  2. import thunk from 'redux-thunk';
  3. import rootReducer from './reducers/index';
  4. // 创建 store 时,作为中间件引入 redux-thunk
  5. const store = createStore(rootReducer, applyMiddleware(thunk));
  6. export const addTodoAsync = text => {
  7. // 返回函数,其中有 dispatch 参数
  8. return (dispatch) => {
  9. fetch(url).then(res => dispatch(addTodo(res.text)))
  10. }
  11. }

redux 中间件

75EA1F07-68E7-474A-AF00-0857DA2B21F9_1_102_o.jpeg

import { applyMiddleware, createStore } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk':
const logger = createLogger () ;

const store = createStore(
  reducer
  applyMiddleware ( thunk, logger) //会按顺序执行
)
// 自己修改 dispatch,增加 logger
let next = store.dispatch;

store.dispatch = function (action) {
  console.log('dispatching', action);
  next(action);
  console.log('next state', action);
}

image.png