我已将 ErrorComponent 放在 App.js 的顶部,但它无法导航到主屏幕。有没有其他方法可以做到这一点?任何指南将不胜感激。我试过 How to use navigation.navigate from a component outside the stack.navigation 但这似乎对我不起作用。
App.js
export class App extends Component {
render() {
return (
<ErrorInterceptor>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<StackNavigation />
</PersistGate>
</Provider>
</ErrorInterceptor>
);
}
}
ErrorInceptor.js
import React, {Component} from 'react';
import {Text, View, TouchableOpacity} from 'react-native';
export default class ErrorInterceptor extends Component {
state = {hasError: false};
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return {hasError: true};
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
// logErrorToMyService(error, errorInfo);
}
changeState = () => {
// console.log('working');
this.setState({hasError: false});
this.props.navigation.navigate('Home');
};
render() {
if (this.state.hasError) {
// console.log(this.props);
// You can render any custom fallback UI
return (
<View>
<Text> Something Went Wrong..! </Text>
<TouchableOpacity
onPress={() => this.changeState()}
style={{width: '40%'}}>
<Text
style={{
backgroundColor: '#898989',
paddingVertical: 10,
borderRadius: 5,
color: 'white',
width: '100%',
textAlign: 'center',
}}>
Return to Home
</Text>
</TouchableOpacity>
</View>
);
}
return this.props.children;
}
}
答案 0 :(得分:3)
这是因为您的错误边界超出了导航的范围,这就是您无法使用导航道具在屏幕之间导航的原因。
由于范围的原因,来自反应导航的 withNavigation 在这里也不起作用。我认为您唯一可以做的就是在根组件上的组件安装上创建导航道具的引用,并将其设置在您的反应上下文或 redux 存储中,并将其用作参考以访问错误边界类中的导航道具。< /p>