【问题标题】:React pass function to child parent not re rendering将函数传递给子父级而不重新渲染
【发布时间】:2017-09-15 22:41:05
【问题描述】:

我有以下功能:

update() {
    this.currentItem = [];
    //...Populate currentItem

    this.setState({
      currentItem
    });
  }

这样在页面上呈现;

render() {
   const { currentItem } = this.state;
   return {currentItem}
}

然后我将此函数传递给子组件,如下所示:

<Component
   update={this.update.bind(this)}
/>

然后在我的子组件中这样调用它:

let { update } = this.props;
if (typeof update === "function")
  update();

问题是更新功能不会重新呈现我在父页面上更新的内容。据我了解,每当调用 setState 时,也会调用 render 。 render() 似乎被调用了,但它似乎没有显示更新的值 - 为什么会这样,我该如何解决?

我猜这可能与它来自子组件的事实有关?

我尝试了 forceUpdate,但它也没有重新渲染组件 - 我错过了什么?

【问题讨论】:

  • 子组件的初始状态是否包含名为currentItem的属性?
  • 不,currentItem 在父项上
  • 但我试图在父节点上更新它,而不是在子节点上
  • 在您的render 函数中,currentItem 的值是多少(尝试将其输出到控制台)?在您的update 函数中,您分配给this.currentItem,但随后您将变量currentItem 传递给状态,该状态(至少在这篇文章中)似乎没有被初始化。

标签: javascript reactjs render


【解决方案1】:

我只是在这里猜测,但我认为您在构造函数中设置了子组件的初始值,并且您希望它反映的值指向它自己的状态而不是父状态

【讨论】:

    【解决方案2】:

    我需要先将状态设置为加载,然后当我将其设置为loading = false时,它会重新呈现该页面

    this.setState({
          loading:true
        });    
    
    //...Do the work
    
    this.setState({
          loading:false
        });    
    

    【讨论】:

      【解决方案3】:

      尽量避免 this.forceUpdate(),因为这不会触发 shouldComponentUpdate(),这是一种性能在 React 中为您的组件挂钩。正如,我看到你正在将你的状态传递给子组件并试图从那里更新父状态对象,这是违法的。您应该在父组件中创建一个方法并将该方法作为道具传递给子组件。它应该是这样的

      constructor(props) {
          super(props);
          this.state = { loading: false };
          this.update = this.update.bind(this);
      }
      update(newState) {
          this.setState({loading: newState })
      }
      render() {
          return <ChildComponent update={this.update} />
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-03
        • 1970-01-01
        • 2021-03-08
        • 2019-12-04
        • 1970-01-01
        • 2021-08-26
        • 2018-12-28
        • 1970-01-01
        • 2021-10-29
        相关资源
        最近更新 更多