为什么reducer函数只返回代理?还原/工具包 [英] Why reducer function return only proxy? redux/toolkit
问题描述
我在 state 参数(payload)中的 reducer 函数返回唯一的代理:
My reducer function in state parameter (payload) returns the only proxy:
Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true
我的切片是状态代理:
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "user",
initialState: {
currentUser: {
loggined: false,
isAdmin: false,
jwt: false,
},
},
reducers: {
setUser: (state, payload) => {
console.log(state); // here is problem, but payload works very well
},
clearUser: (state) => {},
},
});
export const { setUser, clearUser } = userSlice.actions;
export const currentUser = (state) => state.user.currentUser;
export default userSlice.reducer;
这里是 redux 商店
here is redux store
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "../features/user/userSlice";
export default configureStore({
reducer: {
user: userReducer,
},
});
推荐答案
代理对象
Redux Toolkit 允许您变异"通过使用 Immer 包来创建状态的代理草稿版本.您可以安全地改变 reducer 函数中的 state
变量,因为它是一个代理对象,而不是真正的状态.在幕后,您对代理的更改用于返回反映您更改的状态的新副本.
Proxy Object
Redux Toolkit allows you to "mutate" the state by using the Immer package to create a proxied draft version of the state. You can safely mutate the state
variable in your reducer functions because it is a proxy object and not the true state. Behind the scenes, your mutations of the proxy are used to return a fresh copy of the state that reflects your changes.
当您console.log
state
变量时,您会看到此代理.您需要使用 Immer current
函数,它是 包含在 Redux Toolkit 中 以记录真实值.
When you console.log
the state
variable you are seeing this proxy. You need to use the Immer current
function which is included in Redux Toolkit in order to log the true value.
import { createSlice, current } from "@reduxjs/toolkit";
reducers: {
setUser: (state, action) => {
console.log(action);
console.log(current(state));
state.currentUser = action.payload;
},
}
操作与负载
请注意,reducer 的第二个参数是整个 action
,而不仅仅是 payload
.动作是一个具有type
和payload
属性的对象.此操作对象是在使用负载调用 setUser
时自动创建的.
Action vs Payload
Note that the second argument of the reducer is the whole action
, not just the payload
. The action is an object with properties type
and payload
. This action object is created automatically when calling setUser
with a payload.
setUser({loggined: true, isAdmin: false, jwt: "some string"})
返回动作
{
type: "user/setUser",
payload: {
loggined: true,
isAdmin: false,
jwt: "some string",
}
}
您可以将 reducer 函数编写为 setUser: (state, action) =>
并访问 action.payload
或者您可以将其分解为 setUser:(state, {payload}) =>
得到一个 payload
变量.
You can write your reducer function as setUser: (state, action) =>
and access action.payload
or you can destructure it as setUser: (state, {payload}) =>
to get a payload
variable.
这篇关于为什么reducer函数只返回代理?还原/工具包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!