Reactjs setState asynchronous

落花浮王杯 提交于 2019-12-11 15:49:00

问题


I am building a little search engine and got following problem:

Everytime I enter a query, the last letter is missing. I figured out, that it has something to do with setState and that it is not asynchronous... But I can not come up with a solution fo my case.

Her is my function:

  searchHandler = ({ target: { value } }) => {

  this.setState({ term: value });
    this.updateMessage(value);

    if(this.state.message.length === 0){
      this.setState({hasMoreItems: false})

      this.componentDidMount();
    }else{

  var requestUrl = 'https://questdb.herokuapp.com/all?q='
  fetch(requestUrl + this.state.message).then((response)=>{
      return response.json();
  }) .then((data)=>{
      this.setState({ tracks: data});

  })
}
}


updateMessage = message => this.setState({ message });

Do you have any suggestions for me?

Thanks a lot!


回答1:


In general, you want to use the second argument of setState(), which accepts a callback function which will run with the updated state. Here's an example:

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends React.Component { 
  state = {
    value: '',
  }

  handleChange = (e) => {
    e.preventDefault();
    const { value } = e.target;
    this.setState({ value }, () => {
      console.log('Value is:', this.state.value );
    })
  }

  render() { 
    return (
      <input value={this.state.value} onChange={this.handleChange} />
    )
  }
}

render(<App />, document.getElementById('root'));

Live example here.




回答2:


this.setState() can be passed a callback function that will execute once the state is actually set with the new value. You can use it like so:

this.setState({something: newValue}, () => {
    console.log(this.state.something) // this will print out the new value
});


来源:https://stackoverflow.com/questions/54029244/reactjs-setstate-asynchronous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!