Подтвердить что ты не робот

GetDerivedStateFromProps не вызывается

Я использую React 16.3.1 и next.js.
И я положил getDerivedStateFromProps внутри класса, расширяя PureComponent.

Вот код:

Header.js

import { PureComponent } from 'react'
...

export default class Header extends PureComponent {
  constructor (props) {
    super(props)

    this.colorAnimationProps = {
      animationDuration: '0.4s',
      animationFillMode: 'forwards'
    }

    this.colorAnimationStyle = {
      toColor: {
        animationName: 'toColor',
        ...this.colorAnimationProps
      },
      toTransparent: {
        animationName: 'toTransparent',
        ...this.colorAnimationProps
      }
    }

    this.state = {
      colorAnimation: {},
      headerModal: null
    }
  }

  componentDidMount () {
    if (this.props.isColor) {
      this.setState({colorAnimation: this.colorAnimationStyle.toColor})
    }
  }

  static getDerivedStateFromProps (nextProps, prevState) {
    console.log('should go here')
    if (nextProps.isColor) {
      return {colorAnimation: this.colorAnimationStyle.toColor}
    }
    return {colorAnimation: this.colorAnimationStyle.toTransparent}
  }

  render () {
    ...
  }
}

И вот родитель, который модифицирует prop:

index.js

import { PureComponent } from 'react'

...
import Header from '../components/Header'
import Layout from '../components/Layout'
import { withReduxSaga } from '../redux/store'

class Index extends PureComponent {
  constructor (props) {
    super(props)

    this.state = {
      isHeaderColor: false
    }
  }

  componentDidMount () {
    if (window.pageYOffset > 50) {
      this.setState({isHeaderColor: true})
    }

    window.addEventListener('scroll', (e) => {
      if (window.pageYOffset > 50) {
        this.setState({isHeaderColor: true})
      } else {
        this.setState({isHeaderColor: false})
      }
    })
  }

  render () {
    return (
      <Layout url={this.props.url}>
        <Header isColor={this.state.isHeaderColor} />
        ...
      </Layout>
    )
  }
}

export default withReduxSaga(Index)

Моя проблема: getDerivedStateFromProps не вызывается, когда сменяется. По крайней мере, он должен делать console.log, но это не так.

Может ли кто-нибудь помочь мне?

4b9b3361

Ответ 2

убедитесь, что у вас есть правильные варианты react и react-dom в вашем package.json:

"react": "^16.3.1",
"react-dom": "^16.3.1"