Open jtwang7 opened 2 years ago
引用: Debug draft state in redux-toolkit (immer.js)
当使用 console.log
或调试器在 redux-toolkit reducer 中显示 DraftState
时,我们通常会得到 Immer.js
代理对象,其中包含许多不必要的信息。 (redux-toolkit
默认使用immer.js
)
When using
console.log
ordebugger
to display draftState in redux-toolkit reducer we normally get Immer.js proxy object which contains lots of unnecessary information. (Immer.js is used by redux-toolkit by default)
要显示实际数据,请使用从 @redux/toolkit
导入的 current
函数
To display the actual data use
current
function imported from@redux/toolkit
import { createSlice, current } from '@reduxjs/toolkit'
...
console.log(current(draftState))
在日志输出中,我们只会看到我们的数据。
In the log output we’ll see only our data.
Redux 使用笔记
❇️ Quick Start
✅ Create a Redux Store
创建一个 Redux 仓库 (根 store)
✅ Define Typed Hooks 定制类型化版本的 useSelector / useDispatch:虽然可以将 RootState 和 AppDispatch 类型导入每个组件,但最好创建 useDispatch 和 useSelector 挂钩的类型化版本以供在应用程序中使用:
由于这些是实际变量,而不是类型,因此将它们定义在单独的文件(例如 app/hooks.ts)中很重要,而不是定义在 store 仓库内。这允许您将它们导入到需要使用挂钩的任何组件文件中,并避免潜在的循环导入依赖问题。
✅ Provide the Redux Store to React
创建 store 后,我们可以通过在
src/index.js
中的应用程序周围放置一个 React-Redux<Provider>
来使其对我们的 React 组件可用,导入我们刚刚创建的 Redux store。✅ Create a Redux State Slice
从 Redux Toolkit 导入
createSlice
API。创建切片需要一个字符串名称来标识切片、一个初始状态值以及一个或多个 reducer 函数来定义如何更新状态。创建切片后,我们可以导出生成的 Redux action creators 和整个切片的 reducer 函数。✅ Add Slice Reducers to the Store
我们需要从 counter slice 中导出 reducer 函数,并将其添加到我们的 store 中。通过在 reducer 参数中定义一个字段,我们告诉 store 使用这个 slice reducer 函数来处理对该状态的所有更新。
✅ Use Redux State and Actions in React Components
使用 React-Redux 钩子让 React 组件与 Redux 存储交互。我们可以使用 useSelector 从存储中读取数据,并使用 useDispatch 调度操作。创建一个包含 组件的文件,然后将该组件导入 App.js 并在 中渲染它。
✅ createAsyncThunk