【发布时间】:2017-10-24 09:44:16
【问题描述】:
我对 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()
}
}
【问题讨论】: