1 回答
TA贡献1818条经验 获得超3个赞
你的意思是这样的吗?
https://jsfiddle.net/bq8h7ns9/
class Products extends React.Component {
state = {
productList : [],
statusMsg: "",
};
// READ
getDataFromProductsApi() {
this.setState({
productList: [{ id : 0, name: 'blah1', price: 12.3, category : 'blah' }, { id : 1, name: 'blah2', price: 32.1, category : 'blah' }],
});
}
componentDidMount() {
this.getDataFromProductsApi();
}
// DELETE
deleteProduct = (productId, productName) => {
if (window.confirm("Are you sure? you want to delete")) {
this.setState({
statusMsg: `Product name: ${productName} With the ID: ${productId} was removed!`,
productList: this.state.productList.filter((item) => item.id !== productId),
});
}
};
showProducts = () => {
return (
<table className="customers">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Delete</th>
</tr>
{this.state.productList.map((product) => {
return (
<tr key={product.id}>
<td>{product.id}</td>
<td>{product.name}</td>
<td>{product.category}</td>
<td>{product.price}</td>
<td>
<button
onClick={() => this.deleteProduct(product.id, product.name)}
>
X
</button>
</td>
</tr>
);
})}
</tbody>
</table>
);
};
render() {
return (
<header className="App-header">
<div>
<h1>Products</h1>
<div> {this.state.statusMsg}</div>
{this.showProducts()} {/*running function to show data view */}
</div>
</header>
);
}
}
您已经在更新组件的状态;就是这样setState。您注释掉的行应该类似于this.state.productList.filter((item) => item.id !== productId),filter不是全局函数。
如果您希望组件与 api 保持同步,那么您将需要使用 websockets 或长轮询之类的东西。HTTP 是一种无状态协议。
添加回答
举报