在我的 React Table 中,我有一排復選框。每次我選中任何一個框時,我都想將該特定專案的 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>
);
}
uj5u.com熱心網友回復:
給 useState 設定值是一個異步操作。您需要等到該值設定好。
一種方法是從 useEffect
useEffect(() => {
console.log(newdatatoshow)
}, [newdatatoshow])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/336659.html
標籤:javascript html 数组 反应 下一个.js
上一篇:獲取括號中的單詞作為組正則運算式
下一篇:按包含的前綴過濾陣列
