I'm having trouble to lift the state up in that case:
I have a button which on each click adds element to 'mylist' through 'setMyList'. These elements are 'Child' components (the div className "site" is just a CSS square), and I want that each time I click on one of those components/elements it increments 'count' thanks to 'setCount' in the callback that is given to the 'Child' component in 'setMyList'.
But what happen is that, for instance, I create a square then click on it, 'count' doesn't go further than 1, then with another square created, clicking on it makes 'count' goes up to 2 but not more, and so on.
And when I click back on the first square 'count' is 1, it looks like the state is saved for each 'Child' components instead of incrementing it.
Here are my components:
import React, { useState } from 'react'
import Child from './Child.js'
function Parent() {
const [count, setCount] = useState(0);
const [mylist, setMyList] = useState([])
function increment() {
console.log("TEST")
setCount(count + 1)
}
return (
<div className="App">
<button onClick={() => setMyList([...mylist, <Child onClick={increment}></Child>])}> </button>
<h2>count {count}</h2>
{mylist}
(count should be updated from child)
</div>
);
}
export default Parent
Note that each time a square is clicked on, It does go in 'increment' function because the console log displays, but it goes through setCount withtout doing anything.
import React, { useState } from 'react'
import "./Site.css"
function Child(props) {
return (
<div>
<div className="Site" onClick={props.onClick}></div>
</div>
)
}
export default Child
Thanks in advance
question from:
https://stackoverflow.com/questions/66045355/react-hooks-state-update-applies-only-once-when-called-from-callbacks-in-an-arra 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…