以正确的方式发送数据和删除表单中的行

Proper way to send data and delete rows in form react

我得到了一份产品清单,这些产品包含不同的价格。当用户选择产品时,他可以编辑所有价格。这看起来像这样:

_renderPriceRow() {
  return (
    this.props.product.prices.map((price, i) => {
      return (
        <tr key={'pricerowinput-' + Math.random()}>
          <td >
            <input type="text" className="form-control" defaultValue={price.quantity}/>
          </td>
          <td >
            <input type="text" className="form-control" defaultValue={price.name}/>
          </td>
          <td >
            <input type="text" className="form-control" defaultValue={price.price}/>
          </td>
          <td>
            <button type="button" className="btn btn-sm" aria-label="Delete price" onClick={() => alert("Price deleted")}>
              <span className="glyphicon glyphicon-trash" aria-hidden="true"></span>
            </button>
          </td>
        </tr>
      );
    })
  );
}

我随机化了行的键,以便重新呈现行,就好像它们没有更改一样,如果选择另一个产品,默认值也不会更改。

道具:

const mapStateToProps = (state) => {
  const products = state.products.items;
  const isEmpty = state.products.items === undefined || state.products.items.size === 0 || state.productSelected === null;
  if(isEmpty) {
    return ( {product: null});
  }
  return {
    product: products.get(state.productSelected)
  }
};

因此,产品取自产品(过滤后)列表所在的商店。

对于接下来的步骤,我实际上有两个问题: 1. 如何添加或删除一行? 2. 我如何将 table 中的价格组成一个数组,并将其他产品字段(未显示)组成一个我可以发送的对象?

由于 redux,一切都只是 属性。所以将它们放入组件中很容易。如何把它们弄出来?

如果所有值都保留在您的 Redux 存储中,您必须通过更新该存储来添加和删除值。

您可以将 onChange 处理程序添加到 table 输入字段:

<input
   type="text"
   className="form-control"
   defaultValue={price.quantity}
   onChange={this.props.store.updateField}
/>

其中 updateField 是触发 reducer 更新商店的 Redux 操作。

如果您想要删除整行,您可以在按钮 onClick 中触发一个操作,从存储中删除该条目。您可以推断应该从事件目标中删除哪一行。