gpt4 book ai didi

reactjs - getDerivedStateFromProps 未被调用

转载 作者:行者123 更新时间:2023-12-03 13:16:07 24 4
gpt4 key购买 nike

我使用 React 16.3.1next.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 () {
...
}
}

这是修改 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,但它没有。

这里有人可以帮助我吗?

最佳答案

确保您的 package.json 中的 react react-dom 版本正确:

"react": "^16.3.1",
"react-dom": "^16.3.1"

关于reactjs - getDerivedStateFromProps 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com