Riz*_*ryo 13 reactjs next.js react-16
我用的阵营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 () {
...
}
}
Run Code Online (Sandbox Code Playgroud)
以下是修改道具的父级:
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)
Run Code Online (Sandbox Code Playgroud)
我的问题是:当prop改变时,不会调用getDerivedStateFromProps.至少,它应该做console.log,但事实并非如此.
这里有人可以帮帮我吗?
小智 34
确保您拥有正确的版本,react
并 react-dom
在您的package.json
:
"react": "^16.3.1",
"react-dom": "^16.3.1"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8391 次 |
最近记录: |