在构造函数类中调用函数

时间:2018-05-22 18:23:54

标签: javascript reactjs

我试图在FiveDayWeather类的构造函数中调用getWeather()。我将函数绑定到类的上下文,但是当我尝试在构造函数中调用函数时,它会出错。

我试过了:

this.getWeather()

当这不起作用时:

getWeather()

但是那不起作用

如何在此类中调用getWeather函数?

class FiveDayWeather extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      error: null,
      isLoaded: false,
      days: []
    }

    this.getWeather = this.getWeather.bind(this)

    getWeather()


    console.log(this.state);
  }

  getWeather() {
    axios.get(URL)
      .then(function(response) {
        this.setState({
          days: response
        })
      })
  }

  render() {
    return(
      <div>Placeholder</div>
    )
  }
}

这不是关于从异步调用返回响应

1 个答案:

答案 0 :(得分:2)

根据你的说明:

  

我试图在构造函数

中调用getWeather()

它在构造函数中不起作用。把它放在componentDidMount()生命周期方法中,比如

componentDidMount(){
  this.getWeather();
}

根据您的评论,更新承诺,如下:

  getWeather() {
    axios.get(URL)
      .then((response) => {
        this.setState({
          days: response
        })
      })
  }

箭头功能应该绑定this的上下文

相关问题