未调用 getDerivedStateFromProps [英] getDerivedStateFromProps is not called
问题描述
我使用 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.
代码如下:
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 () {
...
}
}
这里是修改 prop 的父级:
And here is the parent that modifies the prop:
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)
我的问题是:当 prop 发生变化时,不会调用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!