我遇到了React Router v.4的问题。当父组件中的路由匹配并呈现子组件时,子组件的componentDidMount方法会触发父组件传递给它的showAlbum方法。
但是,虽然触发了showAlbum方法,但其中的setState方法不会更新父级的状态。卸载子组件时,showAlbum方法可以正常工作,就像在后续调用中一样。
知道我哪里出错了?
谢谢!
父组件:
export default class AlbumContainer extends Component {
constructor(props) {
super(props)
this.state = {
showAlbum: false
}
}
showAlbum() {
this.setState({
showAlbum: !this.state.showAlbum
})
}
render() {
return (
<section className="border">
<div className="u-innerContainer">
<Route path='/:linkName' render={ (props)=><Album showalbum={ this.showAlbum.bind(this) }/> } />
</div>
</section>
)
子组件:
export default class Album extends Component {
render() {
return (
<section>
<div className="u-innerContainer">
<Link to="/">Back</Link>
<h3>{ 'title' }</h3>
<section>{ 'content' }</section>
</div>
</section>
)
}
componentDidMount() {
this.props.showalbum()
}
componentWillUnmount() {
this.props.showalbum()
}
}
答案 0 :(得分:2)
很抱歉,我没有时间验证解决方案,但您的问题可能是由于根据以前的状态值设置状态造成的。
https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
由于
this.props
和this.state
可能会异步更新,因此您不应该依赖它们的值来计算下一个状态。
尝试通过这种方式设置新状态:
showAlbum() {
this.setState(prevState => ({
showAlbum: !prevState.showAlbum
}));
}
答案 1 :(得分:1)
请在子部件中添加constructor
:
constructor(props) {
super(props)
}