gpt4 book ai didi

reactjs - Redux 工具包根据 api 响应更新状态

转载 作者:行者123 更新时间:2023-12-05 04:43:07 26 4
gpt4 key购买 nike

我是 redux 和 reduxjs/toolkit 的新手,我一直坚持在成功调用 api 后更新状态。我在这里关注文档 -> https://redux-toolkit.js.org/api/createAsyncThunk

import { createSlice } from '@reduxjs/toolkit';
import { loginUser } from './actions';

const userSlice = createSlice({
name: 'user',
initialState: { id: 0, name: '', email: '' },
reducers: {},
extraReducers: (builder) => {
builder.addCase(loginUser.fulfilled, (state, action) => {
// trying to overwrite the state directly like this doesn't work
state = { ...action.payload }
// updating each individual part of the state object does work, but this is not ideal for scalability
// state.id = action.payload.id;
// state.name = action.payload.name;
// state.email = action.payload.email;
});
},

如评论中所述,尝试覆盖整个状态对象是行不通的。没有错误消息,但没有任何反应。但是,更新状态对象的每个单独部分确实有效。

最佳答案

Redux Toolkit 构建于 Immer 之上。 Immer 允许您以两种方式更新状态。

重要提示:请谨慎选择其中之一,切勿同时选择两者。

1。变异状态

builder.addCase(loginUser.fulfilled, (state, action) => {
state.id = action.payload.id;
state.name = action.payload.name;
state.email = action.payload.email;
// NEVER use return when mutating state
});

2。返回新状态

builder.addCase(loginUser.fulfilled, (state, action) => {
// NEVER mutate state when using return
return {
id: action.payload.id,
name: action.payload.name,
email: action.payload.email,
};
});

返回语法可以简化为:

builder.addCase(loginUser.fulfilled, (state, action) => action.payload);

但我不推荐。我认为您最好明确说明 reducer 中的状态变化。这样可以更轻松地了解正在发生的变化。

关于reactjs - Redux 工具包根据 api 响应更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69715812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com