2017-03-04 42 views
3

我想从我的渲染方法外部返回jsx。它在没有API请求的情况下工作,但只要添加请求并添加回调,我就无法返回jsx。我该怎么做呢? renderLocations正在我的渲染方法中调用。如何从具有回调的外部函数返回jsx?

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

难道不明显吗?你从'renderLocations'方法返回什么?在回调中返回不会从外部范围返回。 –

回答

4

你不应该这样做。

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方法或构造函数初始化状态。

1

在你提供的例子,不必返回从你的方法什么。我建议你做这样的事,你可以添加coord国家。

componentDidMount() { 
    this.Geo((coord) => this.setState({coord}); 
}, 

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

我想补充一个'if'只返回如果在状态设置其他任何返回坐标值。 –

相关问题