reactjs 每当重新呈现页面时,React状态挂接都会调用初始状态,但不确定原因

woobm2wo  于 2022-12-22  发布在  React
关注(0)|答案(1)|浏览(110)

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

4nkexdtk

4nkexdtk1#

您应该可以通过为useState提供一个函数来修复此问题,该函数返回您希望使用的初始值,例如useState(() => createNewTileBag())
简要说明如下:

// This is an example function that will wait (roughly) X seconds before returning the value 1
// This will help to illistrate the differences in the two methods.
const expensiveTask = (seconds) => {
    var start = new Date();

    while((new Date() - start) / 1000 < seconds);

    return 1;
}

// This example shows how using a command such as useState(expensiveTask(5)) is processed each render
// The useState code has been split into two lines to improve clarity.
const Example1Component = () => {
    // The expensive value is processed.
    // This expensive value will be processed every render.
    const initialExpensiveValue = expensiveTask(5);

    // The expensive value is passed to the useState to use as the inital value.
    // The expensive value will only be inserted into the state on component mount,
    // on all other renders it is ignored.
    const [expensiveValue, setExpensiveValue] = useState(initialExpensiveValue);

    return (
        <div>
            {expensiveValue}
        </div>
    )
}

// This example shows how using a command such as useState(() => expensiveTask(5)) is processed each render
// The useState code has been split into two lines to improve clarity.
const Example2Component = () => {
    // The function is created (not run).
    // This function will be created on each render.
    // Function creation performace impact in most situations can be considered insignificant.
    const initialExpensiveValueFn = () => expensiveTask(5);

    // The function is passed to the useState and will be run to get the inital value.
    // The function will only be run on component mount, on all other renders it is only created.
    const [expensiveValue, setExpensiveValue] = useState(initialExpensiveValueFn);

    return (
        <div>
            {expensiveValue}
        </div>
    )
}

相关问题