ReactJS:如何在获取数据后渲染组件

ReactJS: How to rerender component after fetching data

本文关键字:组件 数据 获取 ReactJS      更新时间:2023-09-26

所以我有一个组件,它显示从外部API获取的一些数据并保存到localStorage。我放置了一个fetchData()函数来完成这项工作,并从componentWillMount()中调用该函数。它看起来像这样:

  componentWillMount() {
    this.fetchData();
  }
  ...
  fetchData() {
    if(localStorage.myData === undefined) {
      fetch(apiUrl,{
        method: 'GET',
        headers: ...
      })
      .then(function(data) {
        localStorage.setItem('myData', data);
      }).catch(function(error) {
        // error handling
      })
    } else { return true; }
  }

这里的想法是检查每次渲染,如果数据设置在localStorage,否则获取它,保存数据,然后渲染。但是,在数据存储在localStorage中之后,我无法使其呈现。我已经尝试使用this.setState({data: data})代替fetchData函数,但this是未定义的。

我在这里做错了什么?

类中的this与then()函数中的this具有不同的上下文。对于您的特殊情况,您可以执行以下操作

 fetch(apiUrl,{
    method: 'GET',
    headers: ...
  })
  .then(function(data) {
    // This now refers to your component
    this.setState({data: data});  
  }.bind(this))
   .catch(function(error) {
    // error handling
  })

或者像Utro建议的那样,您可以使用不会创建自己的上下文的箭头函数,从而允许您适当地使用this

 fetch(apiUrl,{
    method: 'GET',
    headers: ...
  })
  .then(data => {
    // This now refers to your component
    this.setState({data: data}); 
  }).catch(function(error) {
    // error handling
  })

.then中的这个对象将指向Promise调用的对象,而不是Component的对象。

vat that = this;

将这个变量声明为那个变量然后你可以使用

that.setState({})