React 路由渲染组件不触发父级的 setState

React route rendered component not triggering setState on parent

我对 React Router v.4 有疑问。当父组件中匹配到路由并渲染子组件时,子组件的componentDidMount方法会触发父组件传递给它的showAlbum方法

但是,虽然触发了showAlbum方法,但是里面的setState方法并没有更新parent的状态。卸载子组件后,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()
  }
}

请在子组件中添加constructor

constructor(props) {
    super(props)
}

抱歉,我没时间验证解决方案,但您的问题可能是根据之前的状态值设置状态引起的。

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

尝试通过这种方式设置新状态:

showAlbum() {
    this.setState(prevState => ({
        showAlbum: !prevState.showAlbum
    }));
}