简体   繁体   English

在 componentDidMount 中同步调用 setState

[英]Calling setState inside componentDidMount synchronously

I am beginner in react and I am learning about lifecycle hooks.我是反应的初学者,我正在学习生命周期钩子。 I came across some articles stating don't call setState synchronously inside componentDidMount.我看到一些文章说不要在 componentDidMount 中同步调用 setState。 But we can setState in then block of promise.但是我们可以在 promise 的 then 块中设置状态。

The reason mentioned was setState will cause re-render of the component, which will affect performance.提到的原因是 setState 会导致组件重新渲染,这会影响性能。

My question is, even if I write setState inside then block of promise, re-render will be there anyways, also setState is asynchronous so it won't be called immediately.我的问题是,即使我在 promise 的 then 块中写入 setState,无论如何都会重新渲染,而且 setState 也是异步的,因此不会立即被调用。 So why its not recommended to call setState inside componentDidMount synchronously, And how does writing inside then block of promise solves the problem if there are any.那么为什么不建议在componentDidMount内部同步调用setState,以及promise的then块内部写入如何解决问题。

PS: I have researching on SO for quite a while, but couldn't find answers that says don't call setState synchronously, I found some related answers, but didn't answer my question, and I couldn't get them because they were totally related to some scenario. PS:我研究了很长一段时间,但找不到说不要同步调用 setState 的答案,我找到了一些相关的答案,但没有回答我的问题,我无法得到它们,因为他们完全与某些场景有关。

React setState calls are asynchronous. React setState 调用是异步的。 React decides when to do it efficiently. React 决定何时有效地执行此操作。 For example, multiple setState calls are batched together into one single update.例如,多个 setState 调用被批处理到一个单独的更新中。 The way to get around this is using setStates's 2nd parameter which is a callback that will execute once setState is completed and the component re-rendered.解决这个问题的方法是使用 setStates 的第二个参数,它是一个回调,将在 setState 完成并重新渲染组件后执行。

handleThis = () => {
    this.setState({someVar: someVal}, funcToCallimmediately )
}

To test, console.log the state variable just after setState() and write another console.log inside the "funcToCallimmediately" function.为了测试,console.log state 变量就在 setState() 之后,并在 "funcToCallimmediately" function 中写入另一个 console.log。

Take note that if you need to set the state based on the previous state you should use another method.请注意,如果您需要在之前的 state 的基础上设置 state,您应该使用其他方法。 First, just know that setState's 1st parameter can be an object and can also be a function.首先,只要知道setState的第一个参数可以是object,也可以是function。 So you do it like this...所以你这样做...

this.setState((state, props) => {
  return {counter: state.counter + props.step};
});

To understand more, read more about setState() here.要了解更多信息,请在此处阅读有关setState()的更多信息。 You'll get what you need.你会得到你需要的。

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

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