Javascript ComponentDidCatch在react组件内不工作
我有这个组件。在Javascript ComponentDidCatch在react组件内不工作,javascript,reactjs,react-error-boundary,Javascript,Reactjs,React Error Boundary,我有这个组件。在componentDidMount内部,我创建了一个对象并试图抛出错误。但是my组件DidCatch没有被调用,反而破坏了我的页面 class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { error: null, errorInfo: null }; } componentDidCat
componentDidMount
内部,我创建了一个对象并试图抛出错误。但是my组件DidCatch
没有被调用,反而破坏了我的页面
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
errorInfo: null
};
}
componentDidCatch(error, errorInfo) {
// Catch errors in any child components and re-renders with an error message
this.setState({
error,
errorInfo
});
console.log({ error, errorInfo });
}
componentDidMount() {
const d = {}
console.log(d.d.d)
}
render() {
console.log("458454545454")
if (this.state.error) {
console.log("Error occurred")
}
return(<div>dffdfdfdfdfd</div>)
}
}
类ErrorBoundary扩展React.Component{
建造师(道具){
超级(道具);
此.state={
错误:null,
errorInfo:null
};
}
componentDidCatch(错误,errorInfo){
//捕获任何子组件中的错误,并使用错误消息重新呈现
这是我的国家({
错误,
错误信息
});
log({error,errorInfo});
}
componentDidMount(){
常数d={}
控制台日志(d.d.d)
}
render(){
控制台日志(“45845454”)
if(this.state.error){
console.log(“发生错误”)
}
返回(dffdfdfdfdfd)
}
}
此生命周期是在用户抛出错误后调用的
后代组件
componentDidCatch
不捕获同一组件引发的错误。如果要在捕获错误后呈现某些UI,应添加static getDerivedStateFromError
另外,不捕获在错误边界本身抛出的错误(这就是我添加FaultyComponent
抛出实际错误的原因)
函数FaultyComponent(){
抛出新错误(“测试错误”);
返回故障;
}
类ErrorBoundary扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
hasError:错误
};
}
静态getDerivedStateFromError(错误){
返回{hasError:true};
}
componentDidCatch(错误,errorInfo){
log('componentDidCatch',{error,errorInfo});
}
render(){
if(this.state.hasError){
返回出了问题的地方。;
}
返回此.props.children;
}
}
函数App(){
返回(
);
}
render(,document.getElementById(“根”))代码>
也尝试过这个。我在一个子组件中这样做了,但仍然没有调用componentDidCatch