我用的阵营16.3.1和next.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,但事实并非如此。
这里有人可以帮我吗?
请确保您有两个的正确版本
react
,并react-dom
在您package.json
: