【问题标题】:How do I return jsx from an outside function with callback?如何从带有回调的外部函数返回 jsx?
【发布时间】:2017-07-24 22:01:25
【问题描述】:

我正在尝试从我的渲染方法之外返回 jsx。它在没有 api 请求时工作,但是一旦我添加请求并添加回调,我就无法返回 jsx。我该怎么做呢? renderLocations 在我的渲染方法中被调用。

renderLocations() {
    this.Geo((coord) => {
          return this.state.location.map((location, index) => {
            return (
              <div>
               {coord}
              </div>
            );
          })
        })
    }

【问题讨论】:

  • 这不是很明显吗?你从renderLocations 方法返回什么?返回内部回调不会从外部范围返回。

标签: reactjs callback


【解决方案1】:

你不应该这样做。

A.你没有从renderLocations返回任何东西

B.如果您正在等待稍后到达的一些数据。在componentWillMount 生命周期方法中启动调用,并在到达时使用this.setState({coord: coord}) 更新组件的状态——这将再次运行render 方法。在渲染方法中,无论您调用renderLocations 方法,传递this.state.coord

然后像这样改变 renderLocations 方法

renderLocations(coord) {
  if (coord) {
    return this.state.location.map((location, index) => {
        return (
          <div>
           {coord}
          </div>
        );
      })
  }
}

另外,不要忘记在getInitialState 方法或构造函数中初始化状态。

【讨论】:

    【解决方案2】:

    在您提供的示例中,您的方法没有返回任何内容。我建议你做这样的事情,你可以在状态中添加coord

    componentDidMount() {
      this.Geo((coord) => this.setState({coord});
    },
    
    renderLocations() {
      const {coord} = this.state
      return this.state.location.map((location, index) => {
        return (
          <div>
           {coord}
          </div>
        );
      })
    }
    

    【讨论】:

    • 我会添加一个if 以仅在状态中设置了坐标值时返回,否则不返回任何内容。
    猜你喜欢
    • 1970-01-01
    • 2018-05-19
    • 2018-08-19
    • 2023-01-19
    • 2022-12-03
    • 2023-02-23
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多