javascript - 在构造函数类中调用函数

标签 javascript reactjs

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

我试过:

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

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

最佳答案

根据您的说明:

I am trying to call the getWeather() inside of the constructor

它不会在构造函数中工作。将它放在 componentDidMount() 生命周期方法中,比如

componentDidMount(){
  this.getWeather();
}

根据您在下方的评论,像这样更新 promise :

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

箭头函数应该为你绑定(bind)this的上下文

关于javascript - 在构造函数类中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50474209/

相关文章:

javascript - 以实际尺寸显示图像

javascript - 在我的 html 中包含 event.keycode == 13 后 &lt;textarea&gt; 换行不起作用

javascript - 设置react-ga进行转换

javascript - 在顶部滚动表格以添加新行

javascript - 在 React Redux 中使用 Promises

javascript - 在哪里捕获运行语句中的 $location.search() 变量?为了重建国家

javascript - 在 JQuery Cycle 中如何获取当前幻灯片的 src?

javascript - 如何使用纯 JavaScript 删除特定的 <li>

javascript - 测试 react.js 应用程序时无法将鼠标事件分派(dispatch)给所选元素

javascript - 如何在我们的应用程序中使用react-dnd-scrollzone?