不调用getDerivedStateFromProps

Riz*_*ryo 13 reactjs next.js react-16

我用的阵营16.3.1next.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 () {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是修改道具的父级:

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)
Run Code Online (Sandbox Code Playgroud)

我的问题是:当prop改变时,不会调用getDerivedStateFromProps.至少,它应该做console.log,但事实并非如此.

这里有人可以帮帮我吗?

小智 34

确保您拥有正确的版本,react react-dom在您的package.json:

"react": "^16.3.1",
"react-dom": "^16.3.1"
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用 - 我只将`react`升级为`16.3.2`.`react-dom`仍然是'16.2.0` (4认同)

Tom*_*zyk 7

我看到对这个钩子的支持在版本 - 6.0.0-canary.2 of next.JS中修补了.所以我猜你使用的是旧版本.