2017-03-04 14 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(coord) { 
    if (coord) { 
    return this.state.location.map((location, index) => { 
     return (
      <div> 
      {coord} 
      </div> 
     ); 
     }) 
    } 
} 

ようrenderLocations方法を変更する呼び出しているところはどこでもrenderメソッドでは、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'を追加して、状態にcoord値が設定されている場合にのみ返されます。それ以外の場合は何も返しません。 –