fetch, axios not return data timely in reactjs

旧巷老猫 提交于 2019-12-13 04:05:26

问题


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()


回答1:


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>
    );
  }
}


来源:https://stackoverflow.com/questions/49697447/fetch-axios-not-return-data-timely-in-reactjs

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