Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

javascript - Does this.setState return promise in react

I made my componentWillMount() async. Now I can using await with the setState.

Here is the sample code:

componentWillMount = async() => {
  const { fetchRooms } = this.props
  await this.setState({ })
  fetchRooms()
}

So question here is this.setState returns promise because I can use await with it?

Edit

When I put await then it runs in a sequence 1, 2, 3 And when I remove await then it runs 1, 3, 2??

  componentWillMount = async() => {
    const { fetchRooms } = this.props
    console.log(1)
    await this.setState({ } => {
      console.log(2)
    })
    console.log(3)
    fetchRooms()
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can promisify this.setState so that you can use the React API as a promise. This is how I got it to work:

class LyricsGrid extends Component {

  setAsyncState = (newState) =>
    new Promise((resolve) => this.setState(newState, resolve));

Later, I call this.setAsyncState using the standard Promise API:

this.setAsyncState({ lyricsCorpus, matrix, count })
  .then(foo1)
  .then(foo2)
  .catch(err => console.error(err))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...