2017-07-19 5 views
0

ライフサイクルメソッドcomponentDidMountで簡単なフェッチを実行しようとしています。ただし、1秒のタイムアウトがない限り、結果はページに表示されません。私はフェッチの非同期性のためにそれを集めましたが、setTimeoutを使わずにそれを修正するにはどうすればいいですか? componentDidUpdate作業/どのように使用しますか?リアクションライフサイクルメソッド:componentDidMountでフェッチする

 constructor(props) { 
     super(props); 
     this.state = { value: '' }; 
     this.getValue= this.getValue.bind(this); 
     } 

     getValue() { 
      return (
       fetch(url, { 
        method: 'GET', 
       }).then(response => { 
        if (response.status >= 400) { 
         throw new Error('no response: throw'); 
        } 
        return response.json() 
       }).then(response => { 
        this.setState({value: response}); 
       }).catch((error) => { 
        this.setState({ 
         value: 'no response: catch' 
        }) 
       }) 
      ); 
     } 


    componentDidMount(){ 
     //this.getValue(); //does not work 
     setTimeout(() => this.getValue(), 1000); //this works & populates page 
    } 


    render() { 
      return (
        <div> 
        <div>{this.state.value}</div> 
        </div> 
      ) 
    } 

答えて

0

this.getValueメソッドをコンストラクタ内の適切なコンテキストにバインドしてください。あなたがあなたのsetTimeoutにそれを入れると、thisに暗黙的に束縛されている太い矢印の関数になります。

constructor(props) { 
    super(props); 
    this.getValue = this.getValue.bind(this); 
} 

getValue() { ... } 

componentDidMount() { 
    this.getValue(); 
} 
+0

これは通常のメソッド呼び出しですが、バインディングは必要ありません。:) –

+0

どういう意味ですか? 'this.setState'は' this'がコンポーネントインスタンスにバインドされていることを要求します。彼のコードスニペットは、これが起こっている場所を示しておらず、書かれているように、彼は 'フェッチ'のコンテキストから呼び出すようになっています。 –

+0

この回答を確認すると、バインディングが必要なときと理由がわかります。 [**リンク**](https://stackoverflow.com/a/41391426/5185595):) –

関連する問題