我有一个提供上下文的组件(=provider),一些子组件正在使用上下文。
我的提供者还包装了一个 ErrorBoundary React 组件,以防儿童崩溃。从那里,如果发生错误,ErrorBoundary React 组件将更新我上下文中的一些值。
但看起来价值没有更新,我不知道为什么。
我的代码如下所示:
const MyContext = React.createContext<{
state: FsState;
setState: Dispatch<SetStateAction<FsState>> | null;
}>({ state: { ...initState }, setState: null });
const [state, setState] = useState({ ...initState });
const handleError = (error: Error): void => {
setState({
...state,
status: {
...state.status,
hasError: !!error
}
});
};
return (
<MyContext.Provider value={{ state, setState }}>
<ErrorBoundary
onError={handleError}
>
{children}
</ErrorBoundary>
</MyContext.Provider>
);
错误边界组件:
class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
this.props.onError(error);
this.setState({
error,
errorInfo
});
}
render(): React.ReactNode {
const { error, errorInfo } = this.state;
const { children } = this.props;
if (errorInfo) {
return (
<>
<div
>
<h1>
Something went wrong.
</h1>
</div>
<div>{children}</div>
</>
);
}
return children;
}
}
和一个子组件(我的 Provider + ErrorBoundary)
export const ChildElement = () => {
const {
state: { status },
} = useContext(MyContext);
if (status.hasError) {
return <div>I crashed but I'm in safe mode</div>;
}
throw new Error("test test"); // trigger an error
return <div>I'll never work</div>;
};
if loop
尽管调试时componentDidCatch
正确触发了,但我从不进入内部。