首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不调用getDerivedStateFromProps

不调用getDerivedStateFromProps
EN

Stack Overflow用户
提问于 2018-04-05 13:04:30
回答 2查看 11.1K关注 0票数 13

我使用React 16.3.1next.js

我把getDerivedStateFromProps放在扩展PureComponent.的类中

以下是代码:

Header.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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,但它没有。

这里有人能帮我吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-05 17:07:18

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

票数 7
EN

Stack Overflow用户

发布于 2018-04-24 20:46:31

确保您的react react-dompackage.json中都有正确的版本

代码语言:javascript
复制
"react": "^16.3.1",
"react-dom": "^16.3.1"
票数 38
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49673143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档