Redux Toolkit 使用指南

以前我们使用 Redux,通常是指 Redux + React Redux 组合方案,但是现在有了更简化的方案:Redux Toolkit + React Redux,它帮助我们避免了 Redux 的三个常见问题:

1."配置一个 Redux 存储太复杂了"2."我必须添加很多包才能让 Redux 做任何有用的事情"3."Redux 需要太多样板代码"

Redux Toolkit 简化了编写 Redux 逻辑和设置 store 的过程,允许我们编写更容易阅读的更短的逻辑,同时仍然遵循相同的 Redux 行为和数据流。

安装 react-toolkit

npm install @reduxjs/toolkit --save

示例代码:

import { createSlice, configureStore } from '@reduxjs/toolkit'


const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    incremented: state => {
      state.value += 1
    },
    decremented: state => {
      state.value -= 1
    }
  }
})


export const { incremented, decremented } = counterSlice.actions


const store = configureStore({
  reducer: counterSlice.reducer
})


store.subscribe(() => console.log(store.getState()))
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}

Redux工具包 包含了如下API:

configureStore(): 包装 createStore 以提供简化的配置选项和良好的默认预设。它可以自动组合你的切片 reducers,添加您提供的任何 Redux 中间件,默认情况下包含 redux-thunk ,并允许使用 Redux DevTools 扩展。

createReducer(): 为 case reducer 函数提供 action 类型的查找表,而不是编写switch语句。此外,它会自动使用immer 库来让您使用普通的可变代码编写更简单的 immutable 更新,例如 state.todos [3] .completed = true 。

createAction(): 为给定的 action type string 生成一个 action creator 函数。函数本身定义了 toString(),因此它可以用来代替 type 常量。

createSlice(): 接受一个 reducer 函数的对象、分片名称和初始状态值,并且自动生成具有相应 action creators 和 action 类型的分片reducer。

createAsyncThunk: 接受一个 action type string 和一个返回 promise 的函数,并生成一个发起基于该 promise 的pending/fulfilled/rejected action 类型的 thunk。

createEntityAdapter: 生成一组可重用的 reducers 和 selectors,以管理存储中的规范化数据 createSelector 组件 来自 Reselect 库,为了易用再导出。

官方文档:https://redux-toolkit.js.org/

中文:https://redux-toolkit-cn.netlify.app/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值