Day15. Redux的使用

2020-07-13  本文已影响0人  JackLeeVip

补充

过渡动画和axios的补充

  1. CSSTransition
  2. SwitchTransition
  3. TransitionGroup

axios的get如何联系在一起

源码.png

Redux的使用

为什么需要redux

Redux的核心理念 - Store

Redux的核心理念 - action

Redux的核心理念 - reducer

Redux的三大原则

创建一个redux项目

index.js中使用redux

// 1. 导入redux(不能通过ES6的方式)
// commonjs一种实现 -> nodejs
const redux = require('redux');

const initialState = {
  counter: 0
}

// reducer
function reducer(state = initialState, action) {
  switch(action.type) {
    case "INCREMENT":
      return {...state, counter: state.counter + 1}
    case "DECREMENT":
      return {...state, counter: state.counter - 1}
    case "ADD_NUMBER":
      return {...state, counter: state.counter   action.num}
    case "SUB_NUMBER":
      return {...state, counter: state.counter - action.num}
    default: 
      return state;
  }
}

// store(创建的时候需要传入一个reducer)
const store = redux.createStore()

// 订阅store的修改
store.subscribe(() => {
  console.log("counter:", store.getState().counter);
})

// actions
const action1 = {type: "INCREMENT"};
const action2 = {type: "DECREMENT"};

const action3 = {type: "ADD_NUMBER", num: 5};
const action4 = {type: "SUB_NUMBER", num: 5};

// 派发action
store.dispatch(action1);
store.dispatch(action2);
store.dispatch(action3);
store.dispatch(action4);

代码结构优化

小括号不能删掉, 括起来才能当做对象.png

Redux代码和React代码结合起来

调用流程.png 真实开发目录结构.png
上一篇下一篇

猜你喜欢

热点阅读