简体   繁体   English

useState 和 useEffect 的区别

[英]Difference between useState and useEffect

I use useState instead of useEffect and it works fine for displaying data (why?)我使用 useState 而不是 useEffect,它可以很好地显示数据(为什么?)

React.useState(() =>getMovies(), []) React.useState(() =>getMovies(), [])

Note: I added console.log and I get same results注意:我添加了 console.log 并且得到了相同的结果

When a function is passed to useState , this is signaling to React to use lazy initialization - the function will be invoked to calculate the initial value only when the component mounts.当 function 被传递给useState时,这是向 React 发出使用惰性初始化的信号——function 将仅在组件挂载时被调用以计算初始值。

If the value to be put into state can be calculated/retrieved synchronously , this is probably the best design pattern to use - it's short and doesn't require you to later differentiate between whether the state value is undefined or populated.如果可以同步计算/检索要放入 state 的值,这可能是最好的设计模式 - 它很短,不需要您稍后区分 state 值是未定义的还是填充的。

const [stateValue, setStateValue] = useState(calculateExpensiveInitialStateValue);

The time to use useEffect is when the value to be populated can't be computed synchronously, in which case the best approach is to have both useState (for the state) and useEffect (to indicate that you want to run a function to retrieve the state value just once).使用useEffect的时间是当无法同步计算要填充的值时,在这种情况下,最好的方法是同时使用useState (用于状态)和useEffect (表示您要运行 function 来检索state 值只有一次)。

While you theoretically can have a line just like虽然理论上你可以有一条线就像

React.useState(() =>getMovies(), [])

it's pretty confusing, because这很令人困惑,因为

  • The resulting state value returned isn't used未使用返回的结果 state 值
  • useState doesn't accept a second argument dependency array useState不接受第二个参数依赖数组

useEffect is more suited for the task because it doesn't have a return value (unlike useState ), and is more flexible, because it does accept a dependency array. useEffect更适合该任务,因为它没有返回值(不像useState ),而且更灵活,因为它确实接受依赖项数组。 useEffect much more clearly indicates to readers of the code "This callback should run only when the dependency array changes." useEffect更清楚地向代码读者指示“此回调应仅在依赖项数组更改时运行”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM