您好,我正在尝试通过onClick
事件来更新我的状态。 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;
答案 0 :(得分:2)
sixBreaks
是一个对象,您必须更新整个对象才能更新breaks
状态。
const update = () => {
setSixTotal({
...sixBreaks,
breaks: sixBreaks.breaks + 1
});
};
执行setSixTotal(sixBreaks.breaks + 1)
不会适当地更新您的breaks
状态,因为这意味着您正在用state
键的值覆盖breaks
。
答案 1 :(得分:0)
使用传播运算符更新以更新对象属性上的值。进一步了解DCG
const update = () => {
return setSixTotal({...sixBreaks, {breaks: sixBreaks.breaks + 1}})
}
或使用如下的Object.assign函数:
const update = () => {
const updatedValue = Object.assign({}, sixBreaks, {breaks: sixBreaks.breaks + 1})
return setSixTotal(updatedValue)
}
所以像这样更新您的代码:
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;
答案 2 :(得分:0)
你应该做的
const update = () => {
return setSixTotal(prev => ({
...prev,
breaks: prev.breaks + 1
}));
};
不要直接使用sixBreaks.breaks
,因为React不能保证在更新时会保持一致,而是使用我上面写的回调样式来避免错误