Skip to content

Latest commit

 

History

History
71 lines (55 loc) · 1.42 KB

File metadata and controls

71 lines (55 loc) · 1.42 KB

Redux

  • 单一数据源

  • state 是只读的

  • 使用纯函数来执行修改

  • createStore可以帮助创建 store

  • store.dispatch 帮助派发 action , action 会传递给 store

  • store.getState 这个方法可以帮助获取 store 里边所有的数据内容

  • store.subscrible 方法订阅 store 的改变,只要 store 发生改变, store.subscrible 这个函数接收的这个回调函数就会被执行

const redux = require('redux');

const initialState = {
  counter: 0
}

// 创建reducer
const 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.number}
    default: 
      return state;
  }
}

// 根据reducer创建store
const store = redux.createStore(reducer);

store.subscribe(() => {
  console.log(store.getState());
})

// 修改store中的state
store.dispatch({
  type: "INCREMENT"
})
// console.log(store.getState());

store.dispatch({
  type: "DECREMENT"
})
// console.log(store.getState());

store.dispatch({
  type: "ADD_NUMBER",
  number: 5
})
// console.log(store.getState());

redux中间件,如:

  • redux-thunk:用于异步操作
  • redux-logger:用于日志记录
const store = createStore(
  reducer,
  applyMiddleware(thunk, logger)
);