提取,axios无法在reactjs中及时返回数据 [英] fetch, axios not return data timely in reactjs

查看:267
本文介绍了提取,axios无法在reactjs中及时返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

componentWillMount()中,我调用fetch方法来获取数据.但是当fetch未加载时.该组件是render.

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

如何解决.如何在render()之前获取加载的内容

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

推荐答案

您不能.在获取数据并送入组件时,通常需要检查是否有任何数据.如果不存在,则不渲染任何内容或渲染无数据"之类的内容.或在那里显示微调框.为此,使用componentDidMount.

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

这篇关于提取,axios无法在reactjs中及时返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆