最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use setTimeout after setState in react to avoid async issue - Stack Overflow

programmeradmin1浏览0评论

I often do this

this.setState({
something: this.state.something + 1
})

setTimeout(() => { this.props.somefunction(this.state.something) },100);

Is this even correct? but this at least solved my problem. If I don't do timeout here somefunction which is declared in my parent ponent will received an undefined param. I guess doing this.props.somefunction() is executed before setState is done?

I often do this

this.setState({
something: this.state.something + 1
})

setTimeout(() => { this.props.somefunction(this.state.something) },100);

Is this even correct? but this at least solved my problem. If I don't do timeout here somefunction which is declared in my parent ponent will received an undefined param. I guess doing this.props.somefunction() is executed before setState is done?

Share Improve this question asked May 29, 2017 at 0:41 Alan JenshenAlan Jenshen 3,2399 gold badges26 silver badges37 bronze badges 1
  • What's the purpose? Trying to guess when setState will finish? – Dave Newton Commented May 29, 2017 at 0:43
Add a ment  | 

3 Answers 3

Reset to default 5

No, that's not a good pattern. async functions should have a callback parameter that you can use, and looking at the docs, there is one.

Make your function the second parameter to setState.

this.setState({...}, () => {
    this.props.somefunction(this.state.something);
}

The reason using setTimeout here is bad, is because you're taking a chance. You're saying, "I don't know how long this async operation will take, but I'm don't expect it to take longer than 100 ms, so I'm going to take a chance." But of course, you have no idea how long it will take.

The callback parameter ensures that the function will run after the async operation pletes, so you don't need to cross your fingers.

The official documentation remends that you put your "callback logic" inside ponentDidUpdate() instead of the seconds parameter of setState().

The second parameter to setState() is an optional callback function that will be executed once setState is pleted and the ponent is re-rendered. Generally we remend using ponentDidUpdate() for such logic instead.

Here's an example how to do this:

this.setState({
  something: this.state.something + 1
})

ponentDidUpdate(prevProps, prevState) {
  if (this.state.something !== prevState.something) {
    this.props.somefunction(this.state.something); // the state of something has changed -> execute callback function 
  }
}

Using setTimeout to run actions on action plete is generally bad practice and the devs at facebook definitely took that into consideration. Which is why they have a callback method as the second argument for setState.

setState({ something: newState }, () => {
   // Run dependant actions here
})
发布评论

评论列表(0)

  1. 暂无评论