React库存管理系统:新增商品后如何更新State实现无刷新页面
解决React库存管理系统新增商品后实时更新State的问题
我正在开发一款库存管理系统,点击保存按钮新增商品时,希望将POST请求返回的数据添加至包含所有历史商品的State数组中,无需刷新页面即可看到更新效果。目前的代码无法实现该功能,接口返回数据格式如下:
{ "id": null, "product": { "productid": null, "category": "7", "price": 7, "name": "mario", "instock": true }, "_id": "65720598b1e57eb76e2f5658", "__v": 0 }
以下是修改后的完整代码,可实现实时更新功能:
import React, { Component } from 'react' const RESET_VALUES = {id: '', category: '', price: '', name: ''} class ProductForm extends Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this) this.handleSave = this.handleSave.bind(this) this.state = { product: Object.assign({}, RESET_VALUES), errors: {}, products: [] // 初始化历史商品数组 } } handleChange(e) { const target = e.target const value = target.value const name = target.name this.setState((prevState) => { // 通过展开运算符创建新对象,避免直接修改原state return { product: { ...prevState.product, [name]: value } } }) } handleSave = async (e) => { e.preventDefault(); const backendURL = 'http://localhost:5000/product/create'; const { product } = this.state; try { const response = await fetch(backendURL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(product) }); if (response.ok) { const data = await response.json(); console.log(data) // 提取接口返回的实际产品数据,并添加唯一标识 const newProduct = { ...data.product, _id: data._id }; this.setState(prevState => ({ // 用数组展开运算符添加新产品,保证状态不可变性 products: [...prevState.products, newProduct], product: { ...RESET_VALUES }, errors: {} })); console.log('Product saved successfully!', newProduct); } else { console.error('Error saving product:', response.statusText); } } catch (error) { console.error('Error:', error.message); } }; render () { return ( <form> <h4>Add a new product</h4> <p> <label>Name <br /> <input type="text" className="form-control" name="name" onChange={this.handleChange} value={this.state.product.name} /></label> </p> <p> <label>Category <br /> <input type="text" className="form-control" name="category" onChange={this.handleChange} value={this.state.product.category} /></label> </p> <p> <label>Price <br /> <input type="text" className="form-control" name="price" onChange={this.handleChange} value={this.state.product.price} /></label> </p> <input type="submit" className="btn btn-info" value="Save" onClick={this.handleSave}></input> {/* 实时渲染历史商品列表 */} <div className="mt-4"> <h5>Products List</h5> <ul> {this.state.products.map(item => ( <li key={item._id || item.productid}> {item.name} - {item.category} - ${item.price} </li> ))} </ul> </div> </form> ) } } export default ProductForm
关键修改说明
- 初始化历史商品数组:在组件State中添加
products: [],用于存储所有历史商品数据 - 修正状态更新逻辑:
handleChange中不再直接修改原State对象,而是通过展开运算符创建新对象,符合React不可变状态的要求 - 提取正确的产品数据:从接口返回的
data中提取嵌套的product字段,并添加接口返回的_id作为唯一标识 - 更新商品数组:使用
[...prevState.products, newProduct]将新产品添加到数组末尾,保证状态更新的不可变性 - 新增实时渲染:在
render中添加商品列表渲染,验证新增商品后的实时更新效果
内容的提问来源于stack exchange,提问作者captinthor92
相关产品推荐
相关产品推荐

