作者:手机用户2502895293 | 来源:互联网 | 2023-01-03 11:11
在我的reducer中,假设我最初有这种状态:
{
"loading": false,
"data": {
"-L1LwSwW97KkwdSnYvsc": {
"likeCount": 10,
"liked": false, // I want to update this property
"commentCount": 5
},
"-L1EY2_fqzn7sM1Mbf_F": {
"likeCount": 8,
"liked": true,
"commentCount": 22
}
}
}
现在,我想更新对象liked
内部的-L1LwSwW97KkwdSnYvsc
属性,这是data
对象内部并制作它true
.这是我一直在尝试的,但显然,这是错误的,因为在我更新状态后,componentWillReceiveProps
侦听状态更改的组件内的函数不会被触发:
var { data } = state;
data['-L1LwSwW97KkwdSnYvsc'].liked = !data['-L1LwSwW97KkwdSnYvsc'].liked;
return { ...state, data };
你能说明为什么它是错的,我应该如何改变它以使它工作?
1> Li357..:
你在改变状态!当你解构:
var { data } = state;
它与以下相同:
var data = state.data;
所以当你这样做时:
data[…].liked = !data[…].liked
你还在修改state.data
哪个反过来变异state
.这永远不会好 - 使用一些嵌套的扩展语法:
return {
...state,
data: {
...state.data,
'-L1LwSwW97KkwdSnYvsc': {
...state.data['-L1LwSwW97KkwdSnYvsc'],
liked: !state.data['-L1LwSwW97KkwdSnYvsc'].liked
}
}
};