【问题标题】:I am facing issue in map fuction using useEffect and useState我在使用 useEffect 和 useState 的地图功能中遇到问题
【发布时间】:2022-02-10 19:10:37
【问题描述】:

我正在将我的数据与 map 函数绑定,但我遇到了一些错误。我认为问题出在 useState 函数上,当我将数据放入 setAllItems(data) 并调用 map 函数时,如 allItems.map() 所以我在 Dom 中遇到错误,说 allitems 不是函数……我真的很困惑如何将数据放入 useState 并调用 map 函数

      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

【问题讨论】:

  • 你能把fetch之后的控制台打印出来吗?你有那个console.log(data),它显示了什么?

标签: reactjs dictionary html-table use-effect use-state


【解决方案1】:

你的代码sn-p中有很多不相关的代码。以后请尽量发minimal reproducible example,让大家更容易理解您的问题。

这里的问题是这样的:

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

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

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

如果没有看到 console.log 的实际输出,我无法给您实际的属性名称,但请检查您的 fetch 调用实际返回的内容,您应该了解如何从输出中提取实际数据。

【讨论】:

  • 感谢您的建议...在 const data = await res.json();它在控制台中显示所有数据,但是当我尝试在 setAllItems 之类的函数 setAllItems 中设置数据时,它显示错误...可能是我将数据放入函数中的方法错误
  • 我也尝试使用 data.map() 所以它发生错误“数据”未定义
  • data.map() 将不起作用,因为在 fetch 调用收到响应之前,您的数据是未定义的。 allItems 永远不会未定义,因为您在设置 useState 时给它一个默认值 [],所以它是 [],直到您用实际数据替换它。
  • 您的第一条评论已在我的回答中得到解决。您收到的 data 不是数组;在里面寻找你的实际数组
猜你喜欢
  • 2021-07-05
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2022-12-09
  • 2020-11-28
相关资源
最近更新 更多