【问题标题】:removing child component from parent component within map loop从地图循环中的父组件中删除子组件
【发布时间】:2021-09-27 13:47:53
【问题描述】:

在我的父组件中,我有这段代码可以根据 usestate 挂钩文件生成子组件:

files.map((fl) => <AudioFileListItem key={fl.id} id={fl.id} customer_id={customer_id} name={fl.name} s3_url={fl.s3_url} />)

在该子组件中,我希望能够从其父组件的文件挂钩中删除自己,或者只是将自己从渲染中删除。

这是我在子组件中的删除功能:

  const handleAudioDelete = (sound_id) => {
    
    var data = {
      "id": sound_id
    };

    if (window.confirm("Are you sure you want to delete this file?")) {
      axios.post(`/delete-file`, data).then(function(result) {
        //remove item from react list through hook
        console.log(result.data);
      });;
    }

  }

知道我能做什么吗?

更新!

将此添加到父组件并在 prop 中将其传递给子组件。 它成功更新了父组件中文件的值,但不会从视图中删除子组件。我相信这是因为所有子组件都已渲染,并且地图显示没有动态显示文件的值。

  const handleAudioDelete = (sound_id) => {

var data = {
  "id": sound_id
};

if (window.confirm("Are you sure you want to delete this file?")) {
  var index = files.findIndex(function(o){
    return o.id === sound_id;
  })
  if (index !== -1) files.splice(index, 1);

  setFiles(files);
  console.log(files)
}

  /*
  axios.post(`http://localhost:2000/files/delete-file`, data).then(function(result) {
    //remove item from react list through hook
    console.log(result.data);
  });
  */

}

【问题讨论】:

  • axios.post(/delete-file, data) 是否返回删除了一个元素的新数据,还是只是来自后端的成功响应?
  • 这是一个成功的响应,但如果这样更容易,我可以返回删除元素的数据! @DrewReese
  • 好吧,您可以在成功后进行本地过滤,或者让您的 API 返回“新”数据,然后您可以替换本地状态。要么工作。前者的网络密集度较低,因为您基本上是在发送一个“增量”并且它在做工作的前端,后者是在做所有的工作,但网络需求会更多。
  • 您能否分享一个更完整的代码示例,说明正在更新的状态以及它是如何传递来呈现的,以及它是在哪里/如何呈现的?
  • @DrewReese 完整代码已粘贴!

标签: javascript reactjs react-hooks parent-child use-state


【解决方案1】:

假设files是状态,使用元素id过滤状态,返回所有不匹配id属性的文件元素。

const handleAudioDelete = (id) => {
  const data = {
    id
  };

  if (window.confirm("Are you sure you want to delete this file?")) {
    axios.post(`/delete-file`, data)
      .then(function(result) {
        setFiles(files => files.filter(fl => fl.id !== id));
      });
  }
}

【讨论】:

  • 它说 setFiles 没有定义。无论如何我可以将它导入到子组件中?
  • @Juliette 啊,这是/假设handleAudioDeletefiles 状态存在于同一个父组件中,并且handleAudioDelete 作为道具传递到呈现删除按钮的任何位置.如果您可以更新您的问题以包含更全面的父子代码示例,我可以更新为更准确的答案。
  • 实际上我可以将它移到也可以使用的父状态,谢谢!
  • @Juliette 是的,如果你愿意,你可以将 setFiles 状态更新函数传递给子组件。
  • @Juliette 如果我的回答有帮助,请不要忘记投票。如果它解决了您的问题/问题,那么我邀请您接受它。如果还有任何问题,请告诉我。干杯,祝你好运!
猜你喜欢
  • 2018-09-15
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2018-12-25
  • 2022-01-25
  • 2018-03-03
  • 2018-12-10
相关资源
最近更新 更多