我的任务是在数组唯一的情况下向其添加一个数字。
const [items, setItems] = useState(new Set());
const addNumber = () => {
//add elements to an array if it is unique
//is below line is right way to add element ? or i have to write like this - setItems(items.add(input)) ??
items.add(input);
};
<button onClick={addNumber}>ADD Number</button>;
// trying to display the set data, throws an error:map is not a function
<ul>
{
items.map(item=>(<li>{item}</li>))
}
我想遍历集合来显示数据。提前谢谢。
我不会依赖数组长度,因为它可能会改变(添加的项,更糟糕的是删除的项(,所以最简单的方法是获取第一个未使用的id
或最大使用的id
加1(。
后者看起来如下:
const addNumber = () => {
const ids = items.map(({id}) => id),
nextId = Math.max(...ids) + 1
setItems([
...items,
{
id: nextId,
value: input
}
])
}
前者,像这样:
const addNumber = () => {
const ids = items.map(({id}) => id),
nextId = [...Array(x.length+1)]
.map((_,i) => i)
.find(n => !x.includes(n))
setItems([
...items,
{
id: nextId,
value: input
}
])
}
下面的快速现场演示演示了保持记录值和记录id唯一性的方法:
const { useState } = React,
{ render } = ReactDOM,
rootNode = document.getElementById('root')
const App = () => {
const [items, setItems] = useState([]),
[errorMsg, setErrorMsg] = useState(),
onAddItem = e => {
e.preventDefault()
setErrorMsg(null)
const formData = new FormData(e.target),
value = formData.get('myInput'),
ids = items.map(({id}) => id),
nextId = [...Array(ids.length+1)]
.map((_,i) => i)
.find(n => !ids.includes(n))
if(items.some(({value:v}) => v == value)){
setErrorMsg('Value already exists')
} else {
setItems([
...items,
{
id: nextId,
value
}
])
e.target.reset()
}
},
onDeleteItem = _id =>
setItems(items.filter(({id}) => id !== _id))
return (
<div>
<form onSubmit={onAddItem}>
<input name="myInput" />
<input type="submit" value="Add Item" />
{errorMsg && <div className="errorMsg">{errorMsg}</div>}
</form>
{!!items.length &&
(
<ul>
{
items.map(({id, value}) => (
<li key={id}>
{value}
<span
onClick={() => onDeleteItem(id)}
className="removeButton"
>
❌
</span>
</li>
))
}
</ul>
)
}
</div>
)
}
render (
<App />,
rootNode
)
.removeButton {
font-size: 10px;
margin-left: 20px;
}
.removeButton:hover {
cursor: pointer
}
.errorMsg {
font-family: Arial;
font-size: 10px;
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
有几种方法可以做到这一点,首先想到的是,你能使用集合而不是数组吗?默认情况下,集合中的每个元素都是唯一的:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
第二种是通过第一次测试有条件地将项目添加到阵列中,例如
const addNumber = (number) => {
// findIndex will return -1 for items which don't already exist in the array
const index = items.findIndex(item => item === number)
if ( index === -1 ) {
// make a copy of the index array to mutate
const updatedItems = [ ...items ]
updatedItems.push(number)
setItems(updatedItems)
}
}