【问题标题】:How to force child components to rerender?如何强制子组件重新渲染?
【发布时间】:2016-12-31 22:16:18
【问题描述】:

我目前正在初始化父组件中的子组件并将它们放入一个数组中。我正在将一个函数传递给刚刚获得状态的孩子的道具。

 <QuestionContainer
    error={ () => this.state.currentError }
 />

问题是当我在父级中执行this.setState({ currentError: x }) 时,子级不会重新渲染,因为错误道具实际上并没有改变。我试过this.forceUpdate 无济于事。

我知道我可以设计成不需要将子组件初始化为数组的方式,但我想知道在这种情况下如何强制重新渲染。

【问题讨论】:

    标签: javascript html dom reactjs


    【解决方案1】:
    <QuestionContainer
        error={ () => this.state.currentError }
        ref="container"
     />
    

    然后

    this.refs.container.forceUpdate()
    

    不知道这是不是更好的方法

    【讨论】:

      【解决方案2】:

      不清楚为什么要传递一个返回currentError 的值 的函数,而不仅仅是值本身。你就不能这样传递吗:

      &lt;QuestionContainer error={this.state.currentError} />

      然后,在QuestionContainer 的渲染中,像例如这样使用它

      render() {
        return (
          <div>{this.props.error}</div>
        )
      }
      

      如果你想让你的例子工作,你需要调用QuestionContainer中的函数:

      render() {
        return (
          <div>{this.props.error()}</div>
        )
      }
      

      【讨论】:

      • 您可能希望在创建数组之前包含一些var self=this。
      【解决方案3】:

      您还可以在父状态中设置一些计数器变量,并在每次 setState 时将其递增,因此如果您将其传递给孩子,它应该会触发孩子的重新渲染。

      【讨论】:

        猜你喜欢
        • 2018-12-23
        • 1970-01-01
        • 2019-11-12
        • 2014-04-20
        • 2017-05-08
        • 2020-02-13
        • 2019-04-12
        • 2016-05-08
        • 1970-01-01
        相关资源
        最近更新 更多