我有一个产品清单,这个产品包含不同的价格。当用户选择产品时,他可以编辑所有价格。这看起来像这样:
_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.如何将表中的价格与数组和其他产品字段(未显示)组合成我可以发送的对象?
由于redux,一切都只是一个属性。因此,让他们进入组件很容易。如何解决这些问题?
答案 0 :(得分:1)
如果Redux商店中维护了所有值,则必须通过更新该商店来添加和删除值。
您可以在表输入字段中添加onChange
处理程序:
<input
type="text"
className="form-control"
defaultValue={price.quantity}
onChange={this.props.store.updateField}
/>
其中updateField
是Redux操作,触发reducer更新商店。
如果要删除整行,可以在按钮onClick
中触发一个操作,该操作会从商店中删除该条目。您可以推断应从事件目标中删除哪一行。