почему я не могу получить доступ к статическому свойству в getDerivedStateFromProps () - PullRequest
1 голос
/ 28 октября 2019

Я новичок в React, просто вопрос о статическом свойстве доступа в методе жизненного цикла getDerivedStateFromProps, ниже мой код:

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

  render() {
     ...
  }
}

ошибка:

'counter'не определено no-undef

1 Ответ

1 голос
/ 28 октября 2019

Вы должны использовать 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...