为什么reducer函数只返回代理?还原/工具包

Mil*_* N. 4 reactjs redux redux-toolkit

我的状态参数(有效负载)中的减速器函数返回唯一的代理:

\n
Proxy {i: 0, A: {\xe2\x80\xa6}, P: false, I: false, D: {\xe2\x80\xa6}, \xe2\x80\xa6}\n[[Handler]]: null\n[[Target]]: null\n[[IsRevoked]]: true\n
Run Code Online (Sandbox Code Playgroud)\n

我的切片是状态代理:

\n
import { createSlice } from "@reduxjs/toolkit";\n\nexport const userSlice = createSlice({\n  name: "user",\n  initialState: {\n    currentUser: {\n      loggined: false,\n      isAdmin: false,\n      jwt: false,\n    },\n  },\n  reducers: {\n    setUser: (state, payload) => {\n      console.log(state); // here is problem, but payload works very well\n    },\n    clearUser: (state) => {},\n  },\n});\nexport const { setUser, clearUser } = userSlice.actions;\n\nexport const currentUser = (state) => state.user.currentUser;\n\nexport default userSlice.reducer;\n
Run Code Online (Sandbox Code Playgroud)\n

这是 redux 商店

\n
import { configureStore } from "@reduxjs/toolkit";\nimport userReducer from "../features/user/userSlice";\n\nexport default configureStore({\n  reducer: {\n    user: userReducer,\n  },\n});\n\n
Run Code Online (Sandbox Code Playgroud)\n

Lin*_*ste 12

代理对象

Redux Toolkit 允许您通过使用Immer包创建状态的代理草稿版本来“改变”状态。您可以安全地改变state减速器函数中的变量,因为它是代理对象而不是真实状态。在幕后,您的代理突变用于返回反映您的更改的状态的新副本。

当你使用console.log变量时state,你会看到这个代理。您需要使用Redux Toolkit 中包含的Immer函数current记录真实值。

import { createSlice, current } from "@reduxjs/toolkit"; 
Run Code Online (Sandbox Code Playgroud)
reducers: {
  setUser: (state, action) => {
      console.log(action);
      console.log(current(state));
      state.currentUser = action.payload;
  },
}
Run Code Online (Sandbox Code Playgroud)

行动与有效负载

请注意,reducer 的第二个参数是整体action,而不仅仅是payload。该操作是一个具有属性type和 的对象payloadsetUser当使用有效负载调用时,会自动创建此操作对象。

setUser({loggined: true, isAdmin: false, jwt: "some string"})
Run Code Online (Sandbox Code Playgroud)

返回动作

{
  type: "user/setUser",
  payload: {
    loggined: true,
    isAdmin: false,
    jwt: "some string",
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以将您的减速器函数编写为setUser: (state, action) =>和 访问action.payload,也可以对其进行解构以setUser: (state, {payload}) =>获取payload变量。