问题
I use React 16.3.1 and next.js.
And I put getDerivedStateFromProps inside the class extending PureComponent.
Here is the code:
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 () {
...
}
}
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)
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?
回答1:
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.
回答2:
make sure you have the right versions of both react
and react-dom
in your package.json
:
"react": "^16.3.1",
"react-dom": "^16.3.1"
来源:https://stackoverflow.com/questions/49673143/getderivedstatefromprops-is-not-called