【问题标题】:Error component is not able to navigate in react native错误组件无法在本机反应中导航
【发布时间】:2021-05-20 11:22:36
【问题描述】:

我已将 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;
  }
}

【问题讨论】:

    标签: javascript reactjs react-native react-navigation


    【解决方案1】:

    这是因为您的错误边界超出了导航范围,这就是您无法使用导航道具在屏幕之间导航的原因。

    由于范围的原因,来自反应导航的 withNavigation 在这里也不起作用。我认为您唯一能做的就是在根组件上的组件安装上创建导航道具的引用,并将其设置在您的反应上下文或 redux 存储中,并将其用作访问错误边界类中的导航道具的参考。

    【讨论】:

    • 谢谢。让我试试这个
    • 确保将 store provider 组件包装在错误边界组件之上,以便在其范围内。
    • 不工作。一切都白费了。还有什么办法吗?
    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多