【发布时间】:2021-11-02 21:46:14
【问题描述】:
当我 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;
【问题讨论】:
标签: arrays reactjs object react-hooks