为什么componentDidCatch没有阻止应用程序崩溃?

时间:2017-12-12 12:19:33

标签: javascript reactjs react-native

我正在尝试创建一个“失败的鲸鱼”页面,只要应用程序崩溃就会弹出。

为此,我尝试使用'error boundary'和新的componentDidCatch生命周期方法。 https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

到目前为止我没有成功,无论怎样,错误都会导致应用程序崩溃。

这是复制代码:

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class InnerComponent extends Component {
  render() {
    throw new Error('why isn\'t this working')
    return(
      <View>
        <Text>Why is this rendering?</Text>
      </View>
      )
  }
}

class ErrorBoundary extends Component {
    constructor(props) {
      super(props)
      this.state = { hasError: false }
    }

    componentDidCatch(error, info) {
      this.setState({ hasError: true })
      console.log(error, info)
    }

    render() {
      if (this.state.hasError) {
        return (
          <View>
            <Text>Why is this not rendering?</Text>
          </View>
        )
      }
      return this.props.children
    }
}

export default class App extends Component {
  render() {
    return (
      <ErrorBoundary>
        <InnerComponent/>
      </ErrorBoundary>
    );
  }
}

这是我用同样的问题制作的小吃: https://snack.expo.io/BynlDr6-z

我在这里做错了什么?

谢谢!

0 个答案:

没有答案