为什么我无法在getDerivedStateFromProps()中访问静态属性

时间:2019-10-28 14:58:26

标签: javascript reactjs ecmascript-6

我是React的新手,只是一个关于getDerivedStateFromProps生命周期方法中访问静态属性的问题,下面是我的代码:

export default Child extends Component {
  static counter = 0
  ...
  static getDerivedStateFromProps(props, state) {
     if(counter = 1) {
         ...
     }
     a += 1;
  }

  render() {
     ...
  }
}

错误是

  

未定义“计数器” no-undef

1 个答案:

答案 0 :(得分:1)

您应该使用class name进行访问。

Child.counter

示例。

class Child extends Component {
  static counter = 0;

  static getDerivedStateFromProps(props, state) {
    //"this" is undefined here
    console.log("this === " + this);
     if(Child.counter === 0) {
         console.log("counter is ", Child.counter);
     }
     return null;
  }

  render() {
     return "Hello"
  }
}

您可以尝试使用以下SO代码段查看控制台日志

const {render} = ReactDOM

class Child extends React.Component {
  static counter = -123;
  
  static getDerivedStateFromProps(props, state) {
    //this is undefined here
    console.log("this === " + this);
    console.log("counter is ", Child.counter);
    return null;
  }

  render() {
     return "Hello"
  }
}


render(<Child />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

还请注意,由于getDerivedStateFromProps是静态方法,因此它无权访问组件实例。

以下文章可能会帮助您何时使用它。

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state