[英]Component don't re-render after redux modification
I'm using redux in my app and at first, it works as I want.我在我的应用程序中使用 redux,起初,它可以按我的意愿工作。 When I add something into my state through the reducer, my component is re-rendering as I want.
当我通过减速器向我的 state 添加一些东西时,我的组件正在按照我的意愿重新渲染。 But when I only modify the value of a property inside the state, my component isn't re-rending.
但是,当我只修改 state 内的属性值时,我的组件不会重新渲染。
If you need code I can upload it (or some parts) but I think that the problem is more of the way of thinking.如果您需要代码,我可以上传它(或某些部分),但我认为问题更多的是思维方式。
Exemple of my state我的 state 的例子
state = {
"BaliseSeen": {
"Marseille": [
{
"id": "5566",
"nom": "Notre dame de La Garde",
"type": "Monument",
"vue": true,
},
],
"Toulon": [
{
"id": "1122",
"nom": "Isen Yncrea Méditerranée",
"type": "Monument",
"vue": true,
},
{
"id": "3344",
"nom": "Appartement n°69",
"type": "Monument",
"vue": true,
},
{
"id": "6677",
"nom": "Mairie",
"type": "Info",
"vue": false,
},
],
},
"Medailles": [
{
"ville": "Toulon",
},
],
"User": [],
}
When I add something new like that, it work and re-rendered:当我添加类似的新内容时,它会起作用并重新渲染:
nextState = {...state,
BaliseSeen: {
...state.BaliseSeen, [city]: [...state.BaliseSeen[city], { id: action.value.id, type: action.value.type, nom: action.value.nom, vue: action.value.vue }]
}
}
But when I want to only change the property vue from false to true like that, it work (when I check the state in the app the modification is applied but my component isn't re-rendered:但是当我只想像这样将属性vue从false更改为true时,它可以工作(当我在应用程序中检查 state 时,应用了修改,但我的组件没有重新渲染:
BaliseSeenIndex = state.BaliseSeen[city].findIndex(item => item.id === action.value.id)
nextState = state
nextState.BaliseSeen[city][BaliseSeenIndex].vue = true
(I also tried to delete the element from my state and add it after, but same as before, it work without render my component) So I don't know how to say that the state is modified (我还尝试从我的 state 中删除元素并在之后添加它,但与以前一样,它无需渲染我的组件即可工作)所以我不知道怎么说 state 已修改
As commented;正如评论的那样; you should not mutate, do the following instead
您不应该变异,请改为执行以下操作
//not sure where cityp comes from but I assume it is from the action
return {
...state,
BaliseSeen: {
...state.BaliseSeen,
[city]: state.BaliseSeen[city].map((item) =>
item.id !== action.value.id
? item//not the item we want to edit, return unchanged
: {//item we are looking for, return changed copy
...item,
vue: true,
}
),
},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.