gpt4 book ai didi

javascript - 我可以在 redux 状态下传递简单数组吗?

转载 作者:行者123 更新时间:2023-11-29 10:29:18 24 4
gpt4 key购买 nike

我开始学习更好的redux + reactjs

例如,我有一个新闻或列表缩减程序,它应该返回一个包含新闻项目的数组:

const list = [
{id: 1, title: 'One'},
{id: 2, title: 'Two'},
{id: 3, title: 'Three'}
]

export function newsReducer(state = [], action) {
switch (action.type) {
case 'GET_NEWS':
return list
default:
return state
}
}

这段代码工作正常,但在其他文章中我看到他们用 [...state, ...] 和不可变格式传递参数 ...

那么我可以简单地传递参数还是应该以不可变的格式传递?

谢谢

最佳答案

简而言之:是的,如果最适合您的需求,您可以传入简单的数组。

如果您打算使用一个简单的数组,那么确保在进行修改时返回一个数组。

例如:

export function listChangeReducer = (state = [], action) => {
switch action.type {
case 'ADD_ITEM':
// don't do this because you're mutating your state
// state.push(action.item);
// instead do this
state = state.slice();
state.push(action.item);
// or alternatively you can use the destruct syntax
//[...state, action.item];
return state;

break;
}
};

您不需要在 redux 中使用 immutablejs 数据结构。只是建议这样做,以免您不小心改变数据结构。

documentation声明数据需要是不可变的,因为

Both Redux and React-Redux employ shallow equality checking. In particular:

Redux's combineReducers utility shallowly checks for reference changes caused by the reducers that it calls.

关于javascript - 我可以在 redux 状态下传递简单数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50443145/

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