【问题标题】:React route rendered component not triggering setState on parentReact 路由渲染组件未在父级上触发 setState
【发布时间】: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()
  }
}

【问题讨论】:

    标签: reactjs react-router-v4


    【解决方案1】:

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

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

    由于this.propsthis.state 可能会异步更新,因此您不应依赖它们的值来计算下一个状态。

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

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

    【讨论】:

    • 嗨。是的。我用 setState 的回调函数检查了新状态,它显示了更新的状态。非常感谢。
    【解决方案2】:

    请在子组件中添加constructor

    constructor(props) {
        super(props)
    }
    

    【讨论】:

    • 我做到了。但所描述的行为并没有改变。现在我也得到一个控制台警告:Useless constructor no-useless-constructor
    • 请您为此创建一个 plunker 或 jsfiddle 吗?
    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2018-06-27
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多