如何使用React useState钩子更改每个对象的 boolean 属性?
const [showCard, setShowCard] = useState([
{ id: 1, show: true },
{ id: 2, show: true }
]);
答案 0 :(得分:2)
您可以将函数传递给setShowCard
–请参见Functional updates section in the documentation of useState
。第一个参数是先前的状态,您可以将其映射到例如切换每个项目的show
属性:
setShowCard(prevState => prevState.map(item => ({
...item,
show: !item.show,
})));
可运行的示例:
const { useState } = React;
function App() {
const [showCard, setShowCard] = useState([
{ id: 1, show: true },
{ id: 2, show: true },
]);
function toggle() {
setShowCard(prevState => prevState.map(item => ({
...item,
show: !item.show,
})))
}
return (
<div>
<pre>{JSON.stringify(showCard, null, 2)}</pre>
<button onClick={toggle}>Toggle</button>
</div>
);
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>