【发布时间】:2018-10-28 10:40:42
【问题描述】:
我有一个 es6 react 组件,我希望 state 的初始值依赖于传递的 prop 的初始值,但它的值始终为 false:
AttachStateToProps 组件
<AttachStateToProps VALUE=false />
AttachStateToProps 组件:
class AttachStateToProps extends React.Component {
state = {
stateValue: this.props.VALUE,
}
render() {
console.log('Value of Prop - ', this.props.VALUE)
console.log('Value of State - ', this.state.stateValue)
return null
}
}
每次更改道具VALUE的值时,我都会得到:
`Value of Prop - false` // this changes whenever I change prop value in
<AttachStateToProps />
和
`Value of State - false` // this does not change accordingly.
我认为是 it could be something to do with state/setState being async 和更老的 getinitialState,但我不明白为什么。
【问题讨论】:
-
尝试改变componentDidMount中的状态
-
现在它一直返回
true。 eslint 也抱怨[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)- 我认为这不是一个好的模式
标签: reactjs ecmascript-6 state es6-class react-fiber