我在我的应用程序中使用 redux 进行状态管理。
const addStepReducer = (
stepDetails = [
{
stepId: "001",
stepTitle: "Step Name",
stepDescription:"Step Desc",
},
],
action
) => {
if (action.type === "ADD_STEP") {
stepDetails.push(action.payload);
}
return stepDetails;
};
上面的代码是我的reducer函数。
但是当我重新加载页面时,stepDetails 将仅填充默认值,推送的新值将消失。但其他 redux 存储在重新加载后仍保留其值。
我不明白为什么 redux 会这样。但我知道一件事,如果我们使用分配一个值,它将持续存在,而不是推送,即 stepDetails=action.payload;(如果我们只需要有效负载,这是可能的,但在我的情况下,我需要数组本身)。如果有人知道这个问题请告诉我。
如果您决定像现在一样以 2019 年之前的遗留风格编写 Redux,则不能使用这样的变异逻辑。
一般来说,建议您按照官方教程学习现代 Redux。
在现代 Redux 中,你的代码将如下所示,并且你将被允许使用
.push
import { createSlice } from '@reduxjs/toolkit'
const stepSlice = createSlice({
name: "stepDetails",
initialState: [
{
stepId: "001",
stepTitle: "Step Name",
stepDescription:"Step Desc",
},
],
reducers: {
addStep(state, action) {
state.push(action.payload)
}
}
})
export const { addStep } = stepSlice.actions
const addStepReducer = stepSlice.reducer
在您在这里编写的旧 Redux 减速器中,您不允许编写像
.push
这样的可变函数,而不是
stepDetails.push(action.payload);
你必须这样做
return [...stepDetails, action.payload]
相反。