當我 console.log(id) 它給我陣列中物件的索引而不是我試圖用創建物件的函式分配給它的 id 。所以我的問題是如何從陣列物件中提取特定的鍵值對并使用它來確保洗掉正確的物件?
此外,我對編程真的很陌生。
import logo from "./logo.svg";
import "./App.css";
import React, { useState } from "react";
import { nanoid } from "nanoid";
function App() {
const [text, setText] = useState([]);
const [textMaster, setTextMaster] = useState({
paragraph: "",
id: nanoid(),
});
const handleSubmit = (e) => {
e.preventDefault();
const copy = [...text];
copy.push(textMaster);
setText(copy);
};
const handleClick = (e) => {
handleSubmit(e);
};
const handleClickDelete = (id) => {
console.log(id);
const newText = text.filter((text) => text.id !== id);
setText(newText);
};
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<form onSubmit={handleSubmit}>
<label>
Essay:
<textarea
name="item"
key={textMaster.id}
type="text"
value={textMaster.paragraph}
onChange={(e) => setTextMaster(e.target.value)}
/>
</label>
<button onClick={(e) => handleClick(e)}>
Add new text
</button>
</form>
<ul>
{text.map((item, id) => {
return (
<>
<li key={id}>{item}</li>
<button onClick={() => handleClickDelete(id)}>
Delete
</button>
</>
);
})}
</ul>
</header>
</div>
);
}
export default App;
uj5u.com熱心網友回復:
該map函式將索引作為第二個引數回傳,text它不是它不會包含的物件id。
{
text.map((item, index) => {
return (
<>
<li key={index}>{item}</li>
<button onClick={() => handleClickDelete(index)}>
Delete
</button>
</>
);
})
}
然后,在洗掉函式中,使用索引從陣列中洗掉文本,并使用新陣列更新狀態。
const handleClickDelete = (index) => {
const newTexts = [...text]
newTexts.splice(index, 1) // To remove the index
setText(() => newTexts);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346224.html
