[英]I cant get my state to update using hooks
Hi I am trying to update my state with the onClick
event.嗨,我正在尝试使用
onClick
事件更新我的状态。 The onClick
executes but fails to update the state. onClick
执行但无法更新状态。
import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
const [sixBreaks, setSixTotal] = useState({
breaks: 11,
screen: 15,
hindge: 5
});
const update = () => {
return setSixTotal(sixBreaks.breaks + 1)
}
return (
<div className="App">
<h1>Total Broken: {sixBreaks.breaks}</h1>
<button onClick={() => update()}>
CLICK ME TO INCREMENT
</button>
</div>
);
}
export default App;
sixBreaks
is an object, you will have to update the entire object in order to update the breaks
state. sixBreaks
是一个对象,您必须更新整个对象才能更新breaks
状态。
const update = () => {
setSixTotal({
...sixBreaks,
breaks: sixBreaks.breaks + 1
});
};
Doing setSixTotal(sixBreaks.breaks + 1)
will not propertly update your breaks
state, as that implies that you are overwriting your state
with the values of the breaks
key.执行
setSixTotal(sixBreaks.breaks + 1)
不会正确更新您的breaks
状态,因为这意味着您正在用breaks
键的值覆盖您的state
。
Use the spread operator to update to update the values on your object properties.使用扩展运算符更新以更新对象属性上的值。 Read more about it here
在此处阅读更多相关信息
const update = () => {
return setSixTotal({...sixBreaks, {breaks: sixBreaks.breaks + 1}})
}
or use the Object.assign function like this:或者像这样使用 Object.assign 函数:
const update = () => {
const updatedValue = Object.assign({}, sixBreaks, {breaks: sixBreaks.breaks + 1})
return setSixTotal(updatedValue)
}
So update your code like this:所以像这样更新你的代码:
import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
const [sixBreaks, setSixTotal] = useState({
breaks: 11,
screen: 15,
hindge: 5
});
const update = () => {
setSixTotal({...sixBreaks, {breaks: sixBreaks.breaks + 1}})
}
return (
<div className="App">
<h1>Total Broken: {sixBreaks.breaks}</h1>
<button onClick={() => update()}>
CLICK ME TO INCREMENT
</button>
</div>
);
}
export default App;
You should be doing你应该做
const update = () => {
return setSixTotal(prev => ({
...prev,
breaks: prev.breaks + 1
}));
};
Don't use the sixBreaks.breaks
directly since React won't guarantee that it will be the same at the time of update but rather use the callback style as I wrote above to avoid bugs不要直接使用
sixBreaks.breaks
,因为React 不能保证它在更新时是相同的,而是使用我上面写的回调样式来避免错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.