8秒間ロードしたときに取り消すロードコンポーネントがあります。このコードは動作しますが、それは私には気分が悪く、これを行うためのよりよい方法があるのだろうかと思います。componentWillUnmountでclearTimeoutを改善する方法
this.mounted
を設定せずに、私はエラーを取得する:
Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op. Please check the code for the Loading component.
これは私はそれがthis.seState
と続くので、タイマーが取り消さなっていないことを考えさせます。 componentWillUnmount
にclearTimeout
を設定するとどうなりますか?これを処理するには、グローバルthis.mounted
を使用するよりも良い方法はありますか?
class Loading extends Component {
state = {
error: false,
};
componentDidMount =() => {
this.mounted = true;
this.timer();
};
componentWillUnmount =() => {
this.mounted = false;
clearTimeout(this.timer);
};
timer =() =>
setTimeout(() => {
(this.mounted && this.setState({ error: true })) || null;
}, 8000);
render() {
const { showHeader = false } = this.props;
const { error } = this.state;
return (
<View style={backgroundStyle}>
{showHeader && <HeaderShell />}
{!error &&
<View style={loadingHeight}>
<PlatformSpinner size="large" />
</View>}
{error && <Error code="service" />}
</View>
);
}
}
Loading.propTypes = {
showHeader: PropTypes.bool,
};
Loading.defaultProps = {
showHeader: false,
};
export default Loading;
は、あなたは値を保存する必要がありますどこかで 'setTimeout()'から返され、 'clearTimeout()'に渡されます。その関数参照を渡していますが、これはうまくいきません。 @Pointyが指摘するように – Pointy
には、setTimeoutから返された値を保存する必要があります。これは、 'componentWillUnmount'ライフサイクルメソッドを使用してこの操作を行うのが好ましい場所です。 –
setTimeoutによって返される値は、8秒に達しない限り、やりたくない状態を設定しています。 – Turnipdabeets