我遇到了一个问题,每当我的一个React组件在页面上重新呈现时,所有的状态钩子都调用它们的初始状态(返回数据的函数)。enter image description here
例如,在上面的代码片段中,当我在按下此组件中的某个按钮时调用setTroughLetters()
时,createNewTileBag()
、tileBag.takeRandomTiles(7)
和createNewBoard()
都会再次被调用。enter image description here
并使初始状态为空,但是,这个组件中依赖于初始状态的属性会抛出错误,因为我认为useEffect
是在事实发生之后发生的。
我还尝试了类似的方法,我打算检查tile包是否存在,然后仅在它还不存在时调用createNewTileBag()
。enter image description here
不幸的是,我意识到,在测试tileBag
是否包含任何数据之前,需要初始化它。
有什么办法可以解决我的这个问题吗?
1条答案
按热度按时间4nkexdtk1#
您应该可以通过为
useState
提供一个函数来修复此问题,该函数返回您希望使用的初始值,例如useState(() => createNewTileBag())
。简要说明如下: