javascript - React 尝试从列表中删除项目

标签 javascript reactjs

我正在学习 React,并尝试从列表中删除一个项目。我尝试了几种解决方案,但找不到任何可以使其发挥作用的方法。我需要额外的眼睛来看看我错过了什么......

我的调用删除函数的代码

handleDeletePrice = deletePrice => {

  this.setState(prevState => ({
    // spreads out the previous list and delete the price with a unique id(date)
    priceArr: prevState.priceArr.filter(item => item.date !== deletePrice)
  }));
};

这是我在 hook(?) 组件中调用函数的地方。这会显示价格列表,每个价格框中都有一个删除按钮。

{this.state.priceArr.map((props) => (
              <PriceBox
                {...props}
                key={props.date}
                toggleEditing={this.toggleItemEditing}
                handleDeletePrice={this.handleDeletePrice}
                onChange={this.handleItemUpdate}
              />
            ))}

在单一价格框组件中,我在此处添加了删除价格的点击:

{this.props.handleDeletePrice && (
                  <button
                    type="button"
                    className="delete-btn"
                    onClick={() => this.props.handleDeletePrice()}
                    >
                      X
                    </button>
                    )}

要查看我的完整代码,您可以在 CodeSandBox 上查看我的演示,我在其中加载了 github 存储库以显示我的代码。 https://codesandbox.io/s/github/kikidesignnet/caissa

在此演示中,您单击价格按钮并打开一个弹出窗口。这是这个单页应用程序中的另一个页面。在此窗口中,您可以看到价格列表以及每个价格框中的 X 按钮。我还尝试使用日期作为唯一的ID,因为每个价格应该每天输入一次。换句话说,我尝试使用日期作为唯一ID来删除价格框。

我错过了什么?

最佳答案

我不了解业务领域,但我认为这种方法可以提供帮助

{this.state.priceArr.map((props) => (
              <PriceBox
                {...props}
                key={props.date}
                price={props.price}
                toggleEditing={this.toggleItemEditing}
                handleDeletePrice={this.handleDeletePrice}
                onChange={this.handleItemUpdate}
              />
            ))}
{this.props.handleDeletePrice && (
                  <button
                    type="button"
                    className="delete-btn"
                    onClick={() => this.props.handleDeletePrice(this.props.price)}
                    >
                      X
                    </button>
                    )}

关于javascript - React 尝试从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61194902/

相关文章:

javascript - 清除页面缓存

javascript - 一段时间后暂停闪光

javascript - 匹配 jQuery 中的精确字符串

c# - 在 Blazor 页面中渲染 react 组件

javascript - 根据字符串数组过滤对象数组

javascript - React中的JS渲染

javascript - 如何将 svg 之后的 div 添加到现有 div

reactjs - Wordpress Gutenberg PluginDocumentSettingPanel 不适用于控件?

javascript - 如何在react front中显示 Node 数组

javascript - 使用reactjs时复杂的逻辑应该放在哪里才能方便测试?