惰性初始状态 - 是什么以及在哪里使用它? [英] Lazy initial state - What is and where to use it?

查看:53
本文介绍了惰性初始状态 - 是什么以及在哪里使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React Hooks 的新手!我正在尝试在我的代码中使用 useState.当我使用它时,我发现了一个术语懒惰的初始状态"

I am new to react Hooks! Am trying to make use of useState in my code. While I was using it I found a term "Lazy initial state"

https://reactjs.org/docs/hooks-reference.html

const [state, setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});

但我想不出任何用例,这种懒惰的状态初始化会有用!

But I am not able to think of any useCase where this lazy initializing of state will be useful!

比如我的 DOM 正在渲染并且它需要 state 值,但是我的 useState 还没有初始化它!并且说如果你已经渲染了 DOM 并且 useState ExpensiveComputation 已经完成,DOM 会重新渲染!!

Like say am my DOM is rendering and it needs the state value, but my useState has not yet initialized it yet!! And say if you have rendered the DOM and the useState ExpensiveComputation has finished will the DOM will re-render !!

任何帮助都会有用!

推荐答案

传递给 useState 的参数是 initialState,该值在第一次渲染时初始化您的状态并且在随后的渲染中被忽略.但是想象一下下面的情况

The argument passed to useState is the initialState, the value which initializes your state in the first render and is disregarded in subsequent renders. But imagine the following situation

const Component = () =>{
    const [state, setState] = useState(getInitialHundredItems())
}

想象一下这个在每次渲染时被不必要地调用(记住,即使初始值在下一次渲染时被忽略,初始化它的函数仍然会被调用).

Imagine this being called on each render needlessly (remember even though the initial value is disregarded upon next renders, the function which initializes it still gets called).

对于这样的用例,而不是仅仅提供一个值,您可以传递一个返回初始状态的 function,这个函数只会执行一次(初始渲染),而不是像这样在每次渲染时执行上面的代码将

For use cases like this instead of just provide a value you can pass a function which returns the initial state, this function will only be executed once (initial render) and not on each render like the above code will

const Component = () =>{
    const [state, setState] = useState(getInitialHundredItems)
}

这篇关于惰性初始状态 - 是什么以及在哪里使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆