【问题标题】:Ensuring a function runs after setState确保函数在 setState 之后运行
【发布时间】:2019-04-08 22:43:59
【问题描述】:

我知道 SetState 需要一个回调,我正在使用它。但是,由于某种原因,它在状态更新后没有运行。我做错了吗?

  handleInputChange = (event) => {
        this.setState({
          [name]: event.target.value
        });
          if(event.target.value.length > 1) {
          this.getSuggestions();
          this.setState({
          query: event.target.value,
        }, () => this.getCoordinates)
      }

getCoordinates = () =>{
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode( {"address":this.state.query}, this.onSuccessGetAddress)
  }

【问题讨论】:

  • 为什么要分别调用两次 setState?
  • 有两个输入更新不同的东西。第二个有验证(必须超过 1 个字符)

标签: reactjs


【解决方案1】:

您提供了一个回调函数,它返回函数this.getCoordinates

() => this.getCoordinates

你想提供一个调用this.getCoordinates的回调:

() => this.getCoordinates()

this.getCoordinates

【讨论】:

  • 最后一个和已经写好的有什么不同?
  • 最后一个传递函数作为要执行的引用,你的版本传递一个返回你的函数但之后永远不会被调用的函数。
  • 最后一个等价于() => { const geocoder ... }(完全按照您的定义),只需调用一次即可执行内部代码。这意味着你的相当于() => () => { const geocoder ... },需要“调用两次”才能执行内部代码。
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 2019-11-24
  • 2023-01-24
  • 1970-01-01
相关资源
最近更新 更多