ドキュメントErrorBoundaryに従って実装しようとしていますが、これまでのところ成功しています。
ドキュメントに記載されているのと同じアプローチを使用しました
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
私が達成できないのは、 の関数MyWidget内の子コンポーネントの状態を取得することです。子コンポーネントの状態をエラーとともにサーバーに送信して、デバッグを容易にしたいと考えています。ErrorBoundarycomponentDidCatchErrorBoundary
私がこれまでに試したことは、次refsのように使用することです
<ErrorBoundary childrenRef={this.refs["myWidget"]}>
<MyWidget ref="myWidget"/>
</ErrorBoundary>
そして、子コンポーネントで、getState単に独自の状態を返す関数を作成し、その内部で、提供されたようなものErrorBoundaryを使用して子コンポーネントの状態を取得していますref
render() {
if (this.props.childrenRef) {
console.log(this.props.childrenRef.decoratedRef.current.getState());
}
if (this.state.errorInfo) {
// Error path
console.log(this.state.errorInfo);
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
componentDidCatchこれは仕事をして子コンポーネントの状態を返しますが、内部で参照を使用して状態を取得する同じコードを使用しようとするとthis.props.childrenRef.decoratedRef.current、nullおそらく子コンポーネントにエラーがあり、マウントされていないため、current以前nullは子コンポーネント自体への参照。
これを達成するためのより良い方法はありますか?私は何か間違ったことをしていますか?