如何在redux中更新特定数组项中的单个值 [英] How to update single value inside specific array item in redux
问题描述
我有一个问题,重新呈现状态会导致ui问题,并建议只更新我的reducer中的特定值,以减少页面上的重新呈现量。
I have an issue where re-rendering of state causes ui issues and was suggested to only update specific value inside my reducer to reduce amount of re-rendering on a page.
这是我的州的例子
{
name: "some name",
subtitle: "some subtitle",
contents: [
{title: "some title", text: "some text"},
{title: "some other title", text: "some other text"}
]
}
我目前正在更新它这个
case 'SOME_ACTION':
return { ...state, contents: action.payload }
其中 action.payload
是包含新值的整个数组。但现在我实际上只需更新内容数组中第二项的文本,这样的东西不起作用
where action.payload
is a whole array containing new values. But now I actually just need to update text of second item in contents array, and something like this doesn't work
case 'SOME_ACTION':
return { ...state, contents[1].text: action.payload }
其中 action.payload
现在是我需要更新的文本。
where action.payload
is now a text I need for update.
推荐答案
您可以使用 React Immutability helpers
import update from 'react-addons-update';
// ...
case 'SOME_ACTION':
return update(state, {
contents: {
1: {
text: {$set: action.payload}
}
}
});
虽然我想你可能会做更像这样的事情?
Although I would imagine you'd probably be doing something more like this?
case 'SOME_ACTION':
return update(state, {
contents: {
[action.id]: {
text: {$set: action.payload}
}
}
});
这篇关于如何在redux中更新特定数组项中的单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!