redux

redux 及周边

最简实现

// state dispatch reducer
export const createStore = (reducer, initState) => {
  let state = initState
  let listeners = []

  function getState() {
    return state
  }

  function dispatch(action) {
    state = reducer(state, action)
    listeners.forEach(i => i())
  }

  function subscribe(listener) {
    listeners.push(listener)
    return function unsubscribe() {
      const index = listeners.indexOf(listener)
      listeners.splice(index, 1)
    }
  }

  // init
  dispatch({ type: '@@redux/INIT' })

  return { getState, dispatch, subscribe }
}

redux toolkit

  • 封装了 Redux DevTools Extension

  • 封装了 redux-thunk

  • 封装了 immer

  • 开发模式下检查错误:直接修改 state(在 reducer 外),使用不可序列化的值

  • 避免 action type 重复造成 bug

redux toolkit tips

  • createReducer 内部使用了 immer, 可以直接修改 state

  • createSlice 内部使用了 createReducer, 可以直接修改 state

  • createSlice 根据提供的 name, 自动生成 action type, action creators 和 reducer

  • extraReducer: 多个数据 可能需要监听同一个 action,比如监听用户登出,然后重置数据

  • createAction 生成 action 创建函数, 方便创建 action

const actionCreator = createAction('SOME_ACTION_TYPE') // 重写了actionCreator的toString().
console.log(actionCreator.toString(), actionCreator.type)
// "SOME_ACTION_TYPE"

createAsyncThunk

const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

最后更新于