[英]How can I remove a property from state object in React?
Here are properties of state object:以下是 state object 的属性:
const [items, setItems] = useState({
key1: 'apple',
key2: 'watermelon',
key3: 'banana',
});
I wonder, how I can delete specific property from this state object by handling delete?我想知道,如何通过处理删除从这个 state object 中删除特定属性?
const handleDelete = (e) => { }
Thanks in advance提前致谢
Here's one way: duplicate the object (so React notices the change), delete the key (maybe this is the JavaScript feature you were missing), and set the state.这是一种方法:复制 object(因此 React 会注意到更改), 删除密钥(可能这是您缺少的 JavaScript 功能),然后设置 Z9ED39E2EA931586B6A985A6942EF573
const handleDelete = (e) => {
const newItems = {...items};
delete newItems.key2; // or whichever key you want
setItems(newItems);
}
I'm curious whether there's an Object
helper to do this all in one line.我很好奇是否有一个
Object
助手可以在一行中完成这一切。
@Wyck found a cleaner way, which uses the "rest" aspect of destructuring assignment : @Wyck 找到了一种更简洁的方法,它使用解构赋值的“休息”方面:
const handleDelete = (e) => {
const {key2, ...newItems} = items; // newItems gets all but key2
setItems(newItems);
}
The best way is to use the callback function
from setState
And then return the new object.最好的方法是使用
setState
中的callback function
,然后返回新的 object。
setItems(prevState => {
const {key2, ...newItems} = prevState;
return newItems;
});
If you use this method, wrap your deleteElement
in a useCallback
hook and add items
to the list of dependencies:如果您使用此方法,请将您的
deleteElement
包装在useCallback
挂钩中并将项目添加到依赖items
列表中:
const deleteElement = useCallback((e) => { … }, [items]);
Combine this with the @edemaine solution ☺️将此与@edemaine 解决方案结合使用☺️
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.