简体   繁体   English

React 状态存储整数值的默认值

[英]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.

相关问题 如何存储以前的值而不是将值存储在反应状态的对象数组中 - How can I store previous values instead of storing the value in array of objects in react state 在React-Native应用程序中将DynamoDB中的值存储为整数 - Storing value from DynamoDB as integer in React-Native app 反应:默认初始 State 与道具价值 - React: Default Initial State with Prop Value 通过React状态更改所选选项值时,避免将选择标记的值重置为默认值 - Avoid select tag's value being reset to default when changing selected option values through React state 存储复杂的 React 状态 - Storing complex React state 如果在新状态React中缺少默认状态的值,则保留它 - keep default state's values if it's missing in new state React 从对象参数数组中获取值并在反应中存储为空状态 - Getting value out of array of object parameter and storing into an empty state in react 改变 JSON object 的 state 的反应,将数组存储为值 - Mutate React state of a JSON object Storing Array as a value 难以在 const 中存储值并维护输入值的 state(不是道具) - Difficulty storing values in const and maintain state of the inputted value ( not props) 反应:在 state 中存储功能组件 - React: Storing functional component in state
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM