什么是静态getDerivedStateFromError反应?

时间:2018-11-06 14:43:24

标签: javascript reactjs react-native

我正在了解static getDerivedStateFromError

但是我无法理解何时在组件中使用static getDerivedStateFromError,何时使用componentDidCatch

下面我对static getDerivedStateFromErrorcomponentDidCatch都尝试过的示例,但对我来说它们都一样。

import React, { Component } from 'react';
class Test extends Component {
   constructor(props){
      super(props);
      this.state = {
        hasError: false
      }
   }
   shouldComponentUpdate(nextProps, nextState) {
     return this.props.text != nextProps.text;
   }

   static getDerivedStateFromError(error){
      return { hasError: true }
   }
   componentDidCatch(error, info){
     this.setState({
        hasError: true
     });
   }
   render(){
     const { text } = this.props;
     const { hasError } = this.state;
     return(
       <div>
          {hasError ? <h1>Something went wrong</h1> : <h1>{text}</h1>}
       </div>
     )
   }
}

0 个答案:

没有答案