[英]Update complex object using setState
I have array of data and just want to update whenever user click button:我有数据数组,只想在用户单击按钮时更新:
const [visualQuerryData, setVisualQuerryData] = useState([{
default: {
default: [{
class: '',
property: ''
}],
and: [],
or: [],
},
}]);
In this I just want to update class key that's inside default object在此我只想更新默认 object 内部的 class 密钥
What I did:我做了什么:
setVisualQuerryData((p) => [
...p,
(visualQuerryData[0].default.default[i].class = e),
]);
What output I'm getting:我得到的是什么 output:
[{
default: {
and: []
default: [{
class: 'shanum',
property: ''
}],
or: [],
}
},
"shanum"
]
What is actual output:什么是实际 output:
[{
default: {
default: [{
class: 'shanum',
property: ''
}],
and: [],
or: [],
},
}]
I don't know why at the end same data added what I want to add in class key?我不知道为什么最后相同的数据添加了我想在 class 键中添加的内容?
You could use Immer to make state modifications easier by using the produce
function.您可以使用Immer通过produce
function 使 state 修改更容易。 Immer takes the currentQueryState
and returns a copy ie draft
state so you are not mutating the original state. Immer 获取currentQueryState
并返回一个副本,即draft
state,因此您不会改变原始 state。 This makes state updates more readable.这使得 state 更新更具可读性。
import produce from 'immer';
// Where `e` and `i` are defined in the current stacktrace...
setVisualQuerryData((currentQueryData) =>
produce(currentQueryData, (draft) => {
draft[0].default.default[i].class = e;
})
);
Don't forget to install the dependency:不要忘记安装依赖项:
npm install immer
const onChange = (e) => {
// object copy
const nextValue = {...visualQuerryData};
// change value
nextValue[0].default.default[i].class = e;
// update value
setVisualQuerryData(nextValue)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.