使用 React 更改数组中对象的值
2022-08-21
50
今天在开发 React 的时候,由于 JavaScript 基础知识不够扎实,导致自己在某个地方卡住了。
我想改变这个数组中任意对象的“name”属性值。
Codesandbox: https://codesandbox.io/s/dank-rain-udjcxe?file=/src/App.js
const data = [
{ id: 1, name: "jonas" },
{ id: 2, name: "mark" },
{ id: 3, name: "elon" },
];
我的 App.js 文件
const App = () => {
const [people, setPeople] = useState(data);
const changePerson = (id) => {
// if I click on the button, the "name" value of the current object will change to anything
};
return (
<main>
<section>
{people.map((person) => {
return (
<div className="card" key={person.id}>
{person.name}
<button onClick={() => changePerson(person.id)}>change</button>
</div>
);
})}
</section>
</main>
);
};
export default App;
1个回答
本质上,您需要创建一个更新的数组并进行设置。使用回调方法
setPeople
来更新数组。尝试这样做:
const data = [
{ id: 1, name: "jonas" },
{ id: 2, name: "mark" },
{ id: 3, name: "elon" }
];
const App = () => {
const [people, setPeople] = React.useState(data);
const changePerson = (id) => {
setPeople((prevPeople) =>
prevPeople.map((person) =>
person.id === id ? { ...person, name: "changed" } : person
)
);
};
return (
<main>
<section>
{people.map((person) => {
return (
<div className="card" key={person.id}>
{person.name}
<button onClick={() => changePerson(person.id)}>change</button>
</div>
);
})}
</section>
</main>
);
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Amila Senadheera
2022-08-21