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>
)
}
これは通常のメソッド呼び出しですが、バインディングは必要ありません。:) –
どういう意味ですか? 'this.setState'は' this'がコンポーネントインスタンスにバインドされていることを要求します。彼のコードスニペットは、これが起こっている場所を示しておらず、書かれているように、彼は 'フェッチ'のコンテキストから呼び出すようになっています。 –
この回答を確認すると、バインディングが必要なときと理由がわかります。 [**リンク**](https://stackoverflow.com/a/41391426/5185595):) –