在我的React表中,我有一行复选框。每次选中任何框时,我都希望将该特定项的Id发送到一个空数组,并在取消选中时从同一数组中删除该项。我试图做到这一点,但我目前并没有像预期的那样工作。在第一次单击时,它返回一个空数组,但在第二次单击时添加到数组中。要从数组中删除,我还需要单击两次。Codesanboxlink
这是我目前为止所做的
import "./styles.css";
import { useState } from "react";
export default function App() {
const Defaultdata = [
{
date_listed: "4 hours ago",
id: "7857699961",
delivery_time_frame: "2021-10-25 - 2021-11-14",
distance: "22.8 km",
time_stamp: "2021-10-25 16:36:54",
watched: "yes"
},
{
date_listed: "3 days ago",
id: "8358962006",
delivery_time_frame: "2021-10-18 - 2021-10-24",
distance: "4.3 km",
time_stamp: "2021-10-22 16:54:12"
},
{
date_listed: "4 hours ago",
id: "8146462294",
delivery_time_frame: "2021-10-25",
distance: "4.3 km",
time_stamp: "2021-10-25 16:12:32"
}
];
const [newdatatoshow, setnewdatatoshow] = useState([]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<table>
<thead>
<th></th>
<th>Item 1</th>
<th>Item 2</th>
<th>Item 3</th>
<th>Item 4</th>
</thead>
<tbody>
{Defaultdata.map((item, index) => {
return (
<tr key={index}>
<td>
{" "}
<span
onClick={(e) => {
setnewdatatoshow([...newdatatoshow, item.id]);
if (!e.target.checked) {
setnewdatatoshow(newdatatoshow.filter(function(n){ return n !== item.id }))
//setnewdatatoshow(newdatatoshow.splice(newdatatoshow.findIndex(data) => data === item.id))
}
console.log(newdatatoshow);
}}
>
{" "}
<input type="checkbox" />{" "}
</span>{" "}
</td>
<td>{item.id}</td>
<td>{item.distance}</td>
<td>{item.date_listed}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
设置useState的值是异步操作。您需要等待,直到值设置。
一种方法是从useEffect
useEffect(() => {
console.log(newdatatoshow)
}, [newdatatoshow])
您无法从当前状态访问更新后的状态。有关更多信息,请参阅useState set方法不立即反映更改。
你能做的就是在状态变量更新时触发一个效果,并在那里打印更新后的数组
useEffect(() => {
console.log(newdatatoshow)
}, [newdatatoshow])
要了解更多详细信息,请检查this Array not updating on first click