反应尝试从列表中删除项目

时间:2020-04-13 19:05:34

标签: 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

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

我想念什么?

1 个答案:

答案 0 :(得分:1)

我不了解业务领域,但我认为这种方法会有所帮助

{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>
                    )}
相关问题