[英]React hook useState method updates array unexpectedly
I am learning React hook and tried to update an array value.我正在学习 React 钩子并尝试更新数组值。 What I want to achieve is when the button is clicked, the name and the counter of the first element perform the +1 operation.
我想要实现的是当点击按钮时,第一个元素的名称和计数器执行+1操作。 However, the code performs the operation twice instead.
但是,代码改为执行该操作两次。 So the button shows
所以按钮显示
Initial : Click 0 FirstArgument初始:单击 0 FirstArgument
Click 1 : Click 1 FirstArgument1单击 1 :单击 1 FirstArgument1
Click 2 : Click 3 FirstArgument111单击 2 :单击 3 FirstArgument111
Click 3 : Click 5 FirstArgument11111单击 3 :单击 5 FirstArgument11111
... ...
Here is the code snipe:这是代码狙击:
import React, { useState } from "react";
function HookCount() {
const initState = [
{
counter: 0,
name: "FirstArgument",
},
"SecondArgument",
];
const [variable, setCount] = useState(initState);
const setStateFun = () => {
setCount((prevVariable) => {
let updateList = [...variable];
updateList[0].name = prevVariable[0].name + 1;
updateList[0].counter = prevVariable[0].counter + 1;
updateList[1] = prevVariable[1];
return updateList;
});
};
return (
<div>
<button onClick={setStateFun}>
Click {variable[0].counter} {variable[0].name}
</button>
</div>
);
}
export default HookCount;
The questions that I have are:我的问题是:
Why the code behaves like that.为什么代码会这样。 What I did wrong or what is the proper way to achieve this.
我做错了什么或实现这一目标的正确方法是什么。
If I replace let updateList = [...variable];
如果我替换
let updateList = [...variable];
with let updateList = prevVariable;
let updateList = prevVariable;
the state does not change anymore. state 不再改变。 Why can't we use
prevVariable
instead of spread the array here?为什么我们不能使用
prevVariable
而不是在这里展开数组呢?
I don't see setCount
or variable
defined anywhere it your code, so I cannot guess how you implemented them.我没有在您的代码的任何地方看到
setCount
或variable
定义,所以我无法猜测您是如何实现它们的。 However, setStateFun
is just overcomplicated.然而,
setStateFun
只是过于复杂了。
By using the functional setState
, you already have access to prevVariable
.通过使用功能
setState
,您已经可以访问prevVariable
。 To perform the increment, it can be simplified like so:要执行增量,可以这样简化:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [variable, setCount] = useState([
{
counter: 0,
name: "FirstArgument"
},
"SecondArgument"
]);
const setStateFun = () => {
setCount(prevVariable => [
{
counter: prevVariable[0].counter + 1,
name: prevVariable[0].name + 1
},
prevVariable[1]
]);
};
return (
<div>
<button onClick={setStateFun}>
Click {variable[0].counter} {variable[0].name}
</button>
</div>
);
}
See it here:在这里看到它:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.