我正在开发这个 React Native 项目,用于自学。每次按下提交按钮时,我希望 id 值自动增加。例如,如果最新提交的项目的 id 是 7,我希望新的 ID 是 8。我想如果我能找到我的 ID 行中的最高值,那么我可以向它添加 1 并为新提交的新 id元素。我环顾四周,想出了这样的解决方案:
handleAddToList = () => {
let items = [...this.state.items];
let lastId = Math.max.apply(null, items.id);
let newId = lastId + 1;
items.filter(i => i.title == this.state.text).length === 1
? alert("This item is on the list already.")
: items.push({
id: newId,
title: this.state.text,
found: 0,
value: 0,
icon: "delete"
});
this.setState({ items: items });
};
这是我提交文本的小表格:
<Input
placeholder="Start typing"
label={"Your next shop list item..."}
onChangeText={text => this.setState({ text })}
/>
<Button title="Add to list" onPress={() => this.handleAddToList()} />
我的函数实际上是第一次添加该项目,但是当我添加新项目时,我收到此警告:
Warning: Encountered with two children with the same key, '"-infinity"'.
这就是我列出我的元素的方式:
<ListItem
key={l.id}
title={l.title}
rightIcon={{ name: l.icon, color: "#cc0033" }}
bottomDivider={true}
/>
这意味着我的代码的lastId和newId部分无法正常工作。
对于如何让我的 ID 随着每个新提交的项目而增加的任何帮助,我将不胜感激。
最佳答案
它与您的 lastId
变量有关。可以像这样修复:
Math.max.apply(null, items.map(item => item.id))
关于reactjs - 如何在React Native中每次调用onPress函数时提供自动增量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55862885/