【问题标题】:How to trigger parent componentDidUpdate by click in child component如何通过点击子组件触发父组件DidUpdate
【发布时间】:2021-12-25 19:28:09
【问题描述】:

在我的父组件中,我有一个名为 ListOfItems.js类组件,它列出了一堆对象,如下所示:

class ListOfItems extends Component {
  construction (props) {
    super(props);
    this.state = {
      objectList: []
    }
  }
}

// This gets the list of objects to display
componentDidMount() {
   this.getObjectList();
}

componentDidUpdate(_prevProps, prevState) {

  if( this.state.ObjectList !== prevState.ObjectList) {

     // this is called infinitely which is a problem
     console.log("entered");
     this.getObjectList();
  }
}

getObjectList = () => {
  const input = { id_for_this_list: id }

  fetch( connectToApi, {
     method: "PUT",
     headers: { //stuff}
     body: JSON.stringify(input)
  })
     .then(res => //)
     .then(result => 
        if( result.length >= 0) {
            this.setState( {...this.state, objectList: result });
        }   
     )
     .catch(err=>{console.error(err)});
}

render () {
  return (
    {this.state.objectList.map(item) => {
      <Object 
        objectList={this.objectList}
        data={item}
       //few other props here
      >
    }}
  )
}
     

在我的子组件中,我有一个名为 Object.js功能组件。在此,我有一个删除功能,如果用户选择对象上的“x”图标,该对象将从列表中删除。

// 'x' image that, when clicked on, deletes object from list of objects
// (heavily simplified for stackOverFlow)

<img onClick= {() => { deleteObject() })>

const deleteObject() = () => {
   fetch( connectToApi, {
     method: "DELETE"
   })
      .then(res => //)
      .then(result => //deletion made and confirmed succesful)
      .catch(err => console.error(err))
}

我如何在 ListOfItems.js(父级)中触发 componentDidUpdate(),当我单击 “x "对象(子)上?

顺便说一句,parent 必须是 class 组件child 必须是 function 组件,很遗憾.

【问题讨论】:

  • "Object" 对于 Javascript 中的 any 标识符来说是个糟糕的主意。你为什么要这样对自己? React 组件就是 React 组件,无论是类组件还是函数组件,都只是一个实现细节。根本不应该。父组件需要将回调传递给Object 组件,以便它调用父组件中发生的任何事情。你在传递什么作为道具?
  • 为了简单易懂,我把对象命名为Object。是的,我现在知道功能组件和类组件只是在语法上有所不同,经过一些研究......无论如何,我用@S解决了这个问题。下面是阿根廷的cmets。感谢您的意见。

标签: javascript reactjs onclick parent-child react-class-based-component


【解决方案1】:

当您调用 getObjectList 时,您似乎从未设置父组件的状态,因此这可能对您来说是个问题,我不确定您是否故意将其排除在此摘录之外。

无论哪种方式,您都需要从父组件传递一个函数,该函数设置父组件中的状态。这将导致父级重新渲染。

如果您不想更改状态,您可以调用从父级传递的强制刷新的函数,但这并不理想。

parentResetFunction = () => {
   this.forceUpdate()
}

【讨论】:

  • 我忘记在 getObjectList 中包含 setState!感谢您指出了这一点。我已经在上面的代码中解决了这个问题。
  • 我同意你的看法——我不想执行 forceUpdate(),因为这是有风险的,尽管这是一种更新组件的方法。
  • 为了从设置父组件中保持状态的父函数向下传递,我将如何去做呢?父组件是类组件,子组件是功能组件,顺便说一句(我无法更改)。
  • 你需要在你的父组件中创建一个函数,类似于getObjectList,除了在这个函数中你调用this.setState(etc)来改变你的状态。然后获取该函数并将其作为道具传递给子组件并从子组件运行该函数。
  • 你真是个救命恩人!!!太感谢了。我不知道子组件中的函数调用可以通过道具触发父组件中的函数。我花了几个小时在这上面,你救了我。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多