[英]Using array as react hook useState
I am using array as value of useState我使用数组作为 useState 的值
also I need to change only one element and set it as state我也只需要更改一个元素并将其设置为 state
const Main = () => {
const [test, setTest] = useState([1, 2, 3]);
function TestFunction({state, setState}): JSX.Element {
return (
<div
style={{
border: '1px solid black', height: '100px', width: '100%', display: ' block',
}}
onClick={() => {
const qwer = state;
qwer[2] -= 1;
setState(qwer);
console.log('clicked', state);
}}
>{test}
</div>
);
}
return (
<TestFunction state={test} setState={setTest} />
);
}
console says that the value "test" has been changed,控制台说值“test”已更改,
But it never rerenders it.但它从不重新渲染它。
Am I using wrong?我用错了吗? If so, I want to ask some solution please.如果是这样,我想问一些解决办法。
Thank you very much.非常感谢。
You are not making a copy of an array with the =
operator.您没有使用=
运算符复制数组。 Infact you are mutating the state there.事实上,你正在改变 state 。 Use ...
spread operator:使用...
传播运算符:
onClick={() => {
const qwer = [...state];
qwer[2] -= 1;
setState(qwer);
console.log('clicked', state);
}}
React works on the principle of immutability ; React 的工作原理是不变性; whenever an element changes in your state, you shouldn't mutate the underlying value, but instead construct a brand new object with your changes.每当您的 state 中的元素发生变化时,您不应改变基础值,而应使用您的更改构建一个全新的 object。 This is the only way for React to realize the state has changed as under the hood it does oldState===newState
which will always pass, even if you change an index of an array (since they both refer to the same place in memory).这是 React 意识到 state 已经改变的唯一方法,因为它在后台执行oldState===newState
,它总是会通过,即使你改变了数组的索引(因为它们都指向内存中的同一个位置) .
To apply this here, you would do:要在此处应用它,您需要执行以下操作:
const Main = () => {
const [test, setTest] = useState([1, 2, 3]);
function TestFunction({state, setState}): JSX.Element {
return (
<div
style={{
border: '1px solid black', height: '100px', width: '100%', display: ' block',
}}
onClick={() => {
// ---------- New Changes ---------- \\
// [...state] clones the array here
const qwer = [...state];
qwer[2] -= 1;
setState(qwer);
// Note: This will print the old value, you will need to
// wait for the next re-render to get the new state, or
// just log qwer
console.log('clicked', qwer);
}}
>{test}
</div>
);
}
return (
<TestFunction state={test} setState={setTest} />
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.