为什么'useState'钩子在引用函数时会调用初始状态?
React有一个叫做useState的钩子,在向功能组件添加状态时使用。
该挂钩API参考状态:
:
const [state, setState] = useState(initialState);返回一个有状态值,以及一个更新它的函数。
在初始渲染期间,返回的状态(
state)与作为第一个参数(initialState)传递的值相同。该
setState功能用于更新状态。它接受一个新的状态值并排队重新呈现组件。
该阵营文档状态:
useState()挂钩的唯一参数是初始状态。与类不同,状态不必是对象。如果需要,我们可以保留一个数字或一个字符串。在我们的示例中,我们只需要一个用户点击次数的数字,因此将0变量作为初始状态传递。(如果要在状态中存储两个不同的值,则将调用useState()两次。)
意外行为:
但是,我注意到一些奇怪的, 看似没有记载的 行为。
如果我尝试使用useState挂钩将函数存储为状态,则  。例如
const arbitraryFunction = () => {    console.log("I have been invoked!");
    return 100;
};
const MyComponent = () => {
    // Trying to store a string - works as expected:
    const [website, setWebsite] = useState("stackoverflow"); // Stores the string
    console.log(typeof website);                             // Prints "string"
    console.log(website);                                    // Prints "stackoverflow"
    // Trying to store a function - doesn't work as expected:
    const [fn, setFn] = useState(arbitraryFunction);         // Prints "I have been invoked!"
    console.log(typeof fn);                                  // Prints "number" (expecting "function")
    console.log(fn);                                         // Prints "100"
    return null; // Don't need to render anything for this example...
};
当我们调用时useState(arbitraryFunction),react将调用arbitraryFunction并将其返回值用作状态。
解决方法:
通过将函数引用包装在另一个函数中,我们可以将函数存储为状态。例如
const [fn, setFn] = useState(() => arbitraryFunction)我还没有遇到任何将函数存储为状态的现实原因,但是似乎有人奇怪地做出了明确选择以不同方式对待函数参数的选择。
这个选择可以在整个React代码库的多个地方看到:
initialState = typeof initialArg === 'function' ? initialArg() : initialArg;为什么此看似未记录的功能存在?
我想不出为什么有人希望/期望调用他们的函数引用的任何充分理由,但是也许可以。
如果记录在案,在哪里记录?
回答:
这是记录在这里:
懒惰的初始状态
initialState参数是初始渲染期间使用的状态。在后续渲染中,将忽略它。如果初始状态是昂贵的计算结果,则可以提供一个函数,该函数将仅在初始渲染器上执行:
const [state, setState] = useState(() => {const initialState = someExpensiveComputation(props);
return initialState;
});
将回调传递给setState 也会调用该回调,但是出于不同的原因:
功能更新
如果使用先前状态计算新状态,则可以将函数传递给setState。该函数将接收先前的值,并返回更新的值。这是使用两种形式的setState的计数器组件的示例:
>     function Counter({initialCount}) {>       const [count, setCount] = useState(initialCount);
>       return (
>         <>
>           Count: {count}
>           <button onClick={() => setCount(initialCount)}>Reset</button>
>           <button onClick={() => setCount(prevCount => prevCount -
> 1)}>-</button>
>           <button onClick={() => setCount(prevCount => prevCount +
> 1)}>+</button>
>         </>
>       );
>     }
以上是 为什么'useState'钩子在引用函数时会调用初始状态? 的全部内容, 来源链接: utcz.com/qa/430317.html

