1. import {connect} from 'react-redux'
  2. //参数一 mapStateToprops = {state} => {return {num:state.counter}}
  3. //参数二 mapDispatchToProps = dispatch => {return {add:()=>dispatch({type:'add',payload})}
  4. @connect(
  5. state => ({num:state}),
  6. {
  7. add: ()=>({type:'add'}),
  8. minus:()=>({type:'minus'}),
  9. asyncAdd: ()=>dispatch=>{
  10. //异步返回的是函数
  11. setTimeout(()=>{
  12. dispatch({type:'add',100})
  13. },1000)
  14. }
  15. }
  16. )
  17. class ReduxTest extends Component {}
  • redux 不支持异步操作
  1. // store.js
  2. import {createStore,applyMiddleware} from 'redux';
  3. import logger from 'redux-logger'
  4. const store = createStore(counterReducer,applyMiddleware(logger,thunk));//中间件有顺序
  5. export default store

redux 核心实现

  • 存储状态state
  • 获取状态getState
  • 更新状态dispatch
  • 变更订阅subscribe
  1. export default createStore(reducer,enhancer){
  2. //如果存在enhancer
  3. if(enhancer){
  4. //让createStore 变强
  5. enhancer(createStore)(reducer)
  6. }
  7. let currentState = undefined;
  8. const currentListeners = [];//回调函数数组
  9. function getState(){
  10. return currentState
  11. }
  12. function dispatch(action){
  13. currentState = reducer(currentState,action)
  14. //变更通知 发布订阅模式
  15. currentListeners.forEach(v=>v())
  16. return action
  17. }
  18. function subscribe(cb){
  19. currentListeners.push(cb);
  20. }
  21. //初始化状态
  22. dispatch({type:'@#$$JID'})
  23. return {
  24. getState,
  25. dispatch,
  26. subscribe
  27. }
  28. }
  29. export function applMidderware(...midderwares){
  30. return createStore => (...args)=>{
  31. //完成createStore工作
  32. const store = createStore(...args);
  33. let dispatch = store.dipatch;
  34. cosnt midApi = {
  35. getState: store.getState,
  36. dispatch:(...args) => dispatch(...args)
  37. }
  38. //将来中间件的函数签名如下: function({}){}
  39. const chain = middleware.map(mw => mw(midApi))
  40. dispatch = compose(...chain)(store.dispatch)
  41. //返回全新的store 仅更新强化过的dispatch
  42. return {
  43. ...store,
  44. dispatch
  45. }
  46. }
  47. }
  48. export function compose(...funcs){
  49. return funcs.reduce((left,right)=> (...args)=> right(left(...args));
  50. }
  51. ==============================
  52. const counterReducer = function(state=0,action){
  53. const num = action.payload ||1;
  54. switch(action.type){
  55. case "add":
  56. return state + num;
  57. case "minus":
  58. return state - num;
  59. default:
  60. return state;
  61. }
  62. }
  63. const store = createStore(counterReducer)
  • 自定义中间件
  1. function logger({dispatch,getState}){
  2. //返回真正中间件任务执行函数
  3. return dispatch => action => {
  4. console.log(action.type+'执行了!!');
  5. return dispatch(action);
  6. }