不会调用getDerivedStateFromProps

reactjs React.js

小胖

2020-03-20

我用的阵营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 () {
    ...
  }
}

这是修改道具的父母:

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,但事实并非如此。

这里有人可以帮我吗?

第2525篇《不会调用getDerivedStateFromProps》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
神无 2020.03.20

请确保您有两个的正确版本react ,并 react-dom在您package.json

"react": "^16.3.1",
"react-dom": "^16.3.1"
樱LEY神无 2020.03.20

我看到在next.JS的6.0.0-canary.2版本中修补了对该钩子的支持因此,我猜测您使用的是旧版本。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android