首页 文章

React路由呈现组件不会在父级上触发setState

提问于
浏览
1

我有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()
  }
}

2 回答

  • 1

    对不起,我没有时间验证解决方案,但您的问题可能是由基于先前状态值设置状态引起的 .

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

    因为this.props和this.state可以异步更新,所以不应该依赖它们的值来计算下一个状态 .

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

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

    请在子组件中添加 constructor

    constructor(props) {
        super(props)
    }
    

相关问题