getDerivedStateFromProps

getDerivedStateFromProps

本文介绍了不会调用getDerivedStateFromProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 React 16.3.1 next.js .
然后将 getDerivedStateFromProps 放在扩展 PureComponent 的类中.

I use React 16.3.1 and next.js.
And I put getDerivedStateFromProps inside the class extending PureComponent.

这是代码:

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

这是修改道具的父母:

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,但是不应该.

My problem is: getDerivedStateFromProps is not called when the prop changes. At least, it should do console.log, but it doesn't.

这里有人可以帮助我吗?

Can anybody here help me?

推荐答案

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

I see that support for this hook was patched in version - 6.0.0-canary.2 of next.JS. So I'm guessing you use an older version.

这篇关于不会调用getDerivedStateFromProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 22:07