我在使用useEffect和useState的地图功能方面遇到了问题



我正在用map函数绑定我的数据,但我遇到了一些错误。。我认为问题出在useState函数上,当我把数据放在setAllItems(data(中并调用像allItems.map((这样的map函数时,我在Dom中遇到了allItems不是函数的错误。。。我真的很困惑如何将数据放入useState并调用地图函数

import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import '../StockPage/Stock.css'
import '../StockPage/stockValidation'
import { useFormik, Form, Field } from "formik";
import { Link} from 'react-router-dom';
import axios from "axios"


function Stock() {
const [item, setItems] = useState({
itemName: "",
itemCatagory: "",
itemPrice: "",
stockAmount: ""
})
const [search,setSearch] =useState('');
const [allItems, setAllItems] = useState([]);

useEffect(()=>{

const load = async()=>{
try {
const res = await fetch('http://localhost:4000/stock/list')
const data = await res.json();
// setAllItems(data);

console.log(data)
console.log(allItems);
} catch (error) {
console.log(error)
}
}
load()
}
)

const handleChange = e => {
const { name, value } = e.target
setItems({
...item,
[name]: value
})
}
const itemSubmit = () => {

const { itemName, itemCatagory, itemPrice, stockAmount } = item
if (itemName && itemCatagory && itemPrice && stockAmount) {
axios.post("http://localhost:4000/stock", item)
.then(res => console.log(res))
}
else {
alert("Invalid inputs")
}

}
// Search Records here 
const searchRecords = () =>
{
alert(search)
axios.get(``)
.then(response => {
setAllItems(response.data);
});
}
// Delete Employee Record
const deleteRecord = (productId) =>
{
axios.delete(``)
.then((result)=>{
// loadItemsDetail();
})
.catch(()=>{
alert('Error in the Code');
});
};

return (
<div className="Stock">
<div className="container-fluid">
<div className="row">
{/* insert area */}
<div className="col-lg-4">
<h4 className='text-center ml-4 mb-5'>Create New Records</h4>
{console.log("Item", item)}
{/* <form onSubmit={formik.handleSubmit}> */}
<div>
<div className="mx-auto w-75 ">
<div className="form-group ">
<label htmlFor="itemName">Item Name:</label>
<input type="text" className="form-control" id="id_itemName" name="itemName" value={item.itemName} onChange={handleChange}
placeholder="Item Name" />

</div>
<div className="form-group ">
<label htmlFor="itemCategory">Item Category</label>
<input type="text" className="form-control" id="id_itemCategory" name="itemCatagory" value={item.itemCatagory} onChange={handleChange}
placeholder="Item Category" />

</div>
<div className="form-group">
<label htmlFor="itemPrice">Item Price</label>
<input type="text" className="form-control" id="id_itemPrice" name="itemPrice" value={item.itemPrice} onChange={handleChange}
placeholder="Item Price" />

</div>
<div className="form-group">
<label htmlFor="stockAmount">Stock Amount</label>
<input type="text" className="form-control" id="id_Amount" name="stockAmount" value={item.stockAmount} onChange={handleChange}
placeholder="Amount" />

</div>
</div>
<div className='text-center mt-4'>
<button type="submit" className="btn btn-primary" onClick={itemSubmit}>Enter</button>
</div>

</div>
</div>
{/* detailed area */}
<div className="col-sm-8">
<h5 className="text-center  ml-4 mt-4  mb-5">View Records</h5>
<div className="input-group mb-4 mt-3">
<div className="form-outline">
<input type="text" id="form1" onChange={(e) => setSearch(e.target.value)} className="form-control" placeholder="Search Employee Here" 
style={{ backgroundColor: "#ececec" }} />
</div>
<button type="button" onClick={searchRecords} className="btn btn-success">
<i className="fa fa-search" aria-hidden="true"></i>
</button>
</div>
<table className="table table-hover  table-striped table-bordered ml-4 ">
<thead>
<tr>

<th>Item Name</th>
<th>Category</th>
<th>Item Price</th>
<th>Item Amount</th>
<th>Action</th>

</tr>
</thead>
<tbody>
{console.log(allItems)}
{allItems.map((name) =>{

<tr>
<td>{name.itemName}</td>
<td>{name.itemCatagory}</td>
<td>{name.itemPrice}</td>
<td>{name.stockAmount}</td>
<td>
<a className="text-danger mr-2"
onClick={() => {
const confirmBox = window.confirm(
"Do you really want to delete " + name.itemName
)
if (confirmBox === true) {
deleteRecord(name.id)
}
}}> <i className="far fa-trash-alt" style={{ fontSize: "18px", marginRight: "5px" }}></i> </a>

<Link className=" mr-2" to={`/EditEmployee/editID/${name.id}`}>
<i className="fa fa-edit" aria-hidden="true"></i>
</Link>
</td>
</tr>} )}
</tbody>
</table>
</div>
</div>
</div>
</div>
)
};

export default Stock;``` 

enter code here

您的代码片段中有很多不相关的代码。今后,请尽量制作一个最小限度的可重复示例,让人们更容易理解您的问题。

这里的问题是:

const data = await res.json();
// setAllItems(data);

错误allItems.map is not a function表示allItems不是数组,这意味着这里的data实际上不是数组,但更可能是像这样的对象:

{
data: [...] // your actual array
}

在不看到console.log的实际输出的情况下,我无法为您提供实际的属性名称,但请检查fetch调用实际返回的内容,您应该了解如何从输出中提取实际数据。

最新更新