Hi I am trying to update my state with the onClick
event. The onClick
executes but fails to update the state.
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.
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.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.