不调用getDerivedStateFromProps

时间:2018-04-05 13:04:30

标签: reactjs next.js react-16

我使用 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 () {
    ...
  }
}

这是改变道具的父母:

  

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,但它没有。

这里有人可以帮助我吗?

2 个答案:

答案 0 :(得分:31)

确保reactreact-dom package.json的版本正确:

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

答案 1 :(得分:7)

我看到支持这个钩子was patched in version - 6.0.0-canary.2 of next.JS。所以我猜测你使用旧版本。