我有一个要使用React Hooks更新的对象
const [rowEdit, setRowEdit] = useState({ rowEdit: { "1x0": [1, 1, 1, 1, 1] } });
我用.map遍历数组,所以我有每个元素的索引。如何使第二个值等于0?
答案 0 :(得分:1)
如果0
索引等于map
,则可以返回1
,否则返回当前元素。
示例
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>
答案 1 :(得分:1)
尚不清楚是否要对对象中的所有键执行此操作,但我将假定您执行此操作:
setRowEdit(rows => Object.entries(rows).reduce((obj, [rowId, row]) => ({
...obj,
[rowId]: row.map((col, i) => i === 1 ? 0 : col),
}), {}));
否则:
setRowEdit(rows => ({
...rows,
'1x0': rows['1x0'].map((col, i) => i === 1 ? 0 : col),
}), {}));