[英]React Hooks state update applies only once when called from callbacks in an array of components
I'm having trouble to lift the state up in that case:在这种情况下,我无法抬起 state:
I have a button which on each click adds element to 'mylist' through 'setMyList'.我有一个按钮,每次点击都会通过“setMyList”将元素添加到“mylist”。 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'.
这些元素是“子”组件(div className“站点”只是一个 CSS 正方形),我希望每次单击其中一个组件/元素时,由于回调中的“setCount”,它会增加“计数”被赋予'setMyList' 中的'Child' 组件。
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.但是发生的情况是,例如,我创建一个正方形然后单击它,“计数”不会超过 1,然后创建另一个正方形,单击它会使“计数”上升到 2 但不会更多,等等。
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.当我单击第一个正方形“计数”为 1 时,看起来 state 是为每个“子”组件保存的,而不是增加它。
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.请注意,每次单击正方形时,它都会在“增量” function 中执行 go 因为控制台日志显示,但它会通过 setCount 而没有做任何事情。
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提前致谢
You should use setCount((count) => count + 1)
;你应该使用
setCount((count) => count + 1)
;
This will ensure that setCount
can get the latest count value every time.这样可以保证
setCount
都能获取到最新的计数值。
This is because every time you push Child
, the increment
function will be recreated, and then the count
in the increment
function is actually the value when the increment
function was created
.这是因为每次你按下
Child
时, increment
function 都会重新创建,然后increment
function 中的count
实际上是increment
ZC1C425268E68385D1AB5074C17A9 created
时的值
In addition, you can use React.useCallback
to optimize this.此外,您可以使用
React.useCallback
进行优化。
const increment = React.useCallback(() => {
setCount((count) => count + 1);
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.