Я использую Реагировать 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.info('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.info, но это не так.
Кто-нибудь может мне помочь?
@TheReason Прошу прощения, я забыл поставить код. Я только что обновил свой вопрос. Спасибо.
Откуда у тебя props?
@TheReason Свойства исходят от родительского, index.js. Я только что снова обновил свой вопрос. И еще раз спасибо.
какую версию nextjs вы используете?





Я вижу, что этот хук поддерживает был пропатчен в версии 6.0.0-canary.2 от next.JS. Полагаю, вы используете старую версию.
убедитесь, что у вас есть правильные версии обоих reactа такжеreact-dom в вашем package.json:
"react": "^16.3.1",
"react-dom": "^16.3.1"
У меня это сработало - я обновил только react до 16.3.2. react-dom все еще был на 16.2.0
Где код?