简体   繁体   中英

fetch, axios not return data timely in reactjs

In componentWillMount() i call fetch method to get data. But when fetch not loaded. This component was render .

How to fix it.? how to fetch loaded before render()

You can't. When you getting data and feeding your component generally you need to check if there is any data. If there is not, either render nothing or render something like "No data." or show a spinner there. Use componentDidMount for that.

class App extends Component {
  state = {
    data: "",
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
      fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => response.json())
        .then(json => this.setState( {data: json}));
  }

  render() {
    return (
      <div>
        { this.state.data ? <p>{this.state.data.title}</p>: "No data"}
      </div>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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