[英]Default value for React state storing integer values
I have a selectedId
React state that stores integer values.我有一个存储整数值的selectedId
React 状态。 The state is updated with an id
integer, when an item is selected from a list.当从列表中选择一个项目时,状态会更新为id
整数。 Once selectedId
is set, the user can click a delete
button to delete the selected element, after which selectedId
should be set back to its initial value again.设置selectedId
,用户可以单击delete
按钮删除所选元素,然后应再次将selectedId
设置回其初始值。
What is the recommended default value for selectedId
? selectedId
的推荐默认值是多少? Should it set to null ( useState(null)
and setSelectedId(null)
), or be undefined ( setSelectedId()
)它应该设置为 null( useState(null)
和setSelectedId(null)
),还是未定义( setSelectedId()
)
const [selectedId, setSelectedId] = useState();
const handleSelect = id => {
setIsAlertOpen(true);
setSelectedId(id);
};
<Button onClick={() => {
deleteItem(selectedId)
setSelectedId();
}/>
Create a constant to store the initial value.创建一个常量来存储初始值。 And when you delet the selectid restore it yo initial value.当你删除 selectid 时,它会恢复它的初始值。
const initialValue = null;
const [selectedId, setSelectedId] = useState(initialValue);
const handleSelect = id => {
setIsAlertOpen(true);
setSelectedId(id);
};
<Button onClick={() => {
deleteItem(selectedId)
setSelectedId(initialValue);
}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.