gpt4 book ai didi

javascript - 如何使用 React Hooks 更新对象内数组的特定值?

转载 作者:行者123 更新时间:2023-12-03 13:42:40 24 4
gpt4 key购买 nike

我有一个对象,我想使用 React Hooks 更新它

const [rowEdit, setRowEdit] = useState({ rowEdit: { "1x0": [1, 1, 1, 1, 1] } });

我使用 .map 循环遍历数组,因此我有每个元素的索引。如何使第二个值等于 0?

最佳答案

如果map索引等于1,则可以返回0,否则返回当前元素。

示例

const { useState } = React;

function App() {
const [rowEdit, setRowEdit] = useState({
rowEdit: { "1x0": [1, 1, 1, 1, 1] }
});

function onClick() {
setRowEdit(prevState => ({
...prevState,
rowEdit: {
...prevState.rowEdit,
"1x0": prevState.rowEdit["1x0"].map((row, index) =>
index === 1 ? 0 : row
)
}
}));
}

return (
<div>
<button onClick={onClick}>update row</button>
<div>{JSON.stringify(rowEdit)}</div>
</div>
);
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

关于javascript - 如何使用 React Hooks 更新对象内数组的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55692004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com