gpt4 book ai didi

reactjs - componentDidMount() 中的 setState() 是否被视为反模式

转载 作者:行者123 更新时间:2023-12-03 13:13:31 25 4
gpt4 key购买 nike

我刚刚看了at this discussion关于 componentDidMount() 内的 setState()

You can see that after the render() function, the componentDidMount() function will be called by React. When you put a setState() call in componentDidMount() then you are causing the entire component tree be re-rendered not only the current component - not to forget, the current component did just finished with rendering.

有些人建议将 setState() 调用放在 componentWillMount() 中。在某些情况下,我想获取渲染元素的高度并将其存储为状态,上述方法不起作用。我还看了React官网,它建议在componentDidMount()内部进行Ajax调用,这又违背了上面的想法。

那么,我将 setState() 放入 componentDidMount() 中是错误的吗?如果是,我应该使用什么作为替代方案?

最佳答案

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the constructor() instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.

React docs

Using DidMount makes it clear that data won’t be loaded until after the initial render. This reminds you to set up initial state properly, so you don’t end up with undefined state that causes errors.

Example

TLDR: - 如果构造函数中有所有需要的数据 - 在那里分配 state

constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
}
  • 调用异步操作,在 componentDidMount() 中触摸 DOM

关于reactjs - componentDidMount() 中的 setState() 是否被视为反模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52168047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com