开发者问题收集

TypeError:无法读取未定义的属性(读取“map”)(现有解决方案 dint help)

2021-09-29
760

我检查了其他答案,但这些答案没有帮助。

我无法理解为什么会出现此错误。我通过运行 postman 检查了 api,它提供了正确的数据。我还检查了我的变量。此错误的可能原因是什么。 以下是代码。

const RestaurentList = () => {
      const {restaurants , setRestaurents } = useContext(RestaurentsContext)
      useEffect(async () => {
          const fetchData= async ()=>{
              try{
                  const response = await RestaurentFinder.get("/")
                  setRestaurents(response.data.restaurants)
                  console.log(response);
              }catch(err) { }
          };
        fetchData();
      }, [])
   
    return (
        <div className="list-group">
            <table className="table table-hover table-dark">
               <thead>
                   <tr className="bg-primary">
                      <th scope="col">Restaurent </th>
                      <th scope="col">Location</th>
                      <th scope="col">Price Range</th>
                      <th scope="col">Ratings</th>
                      <th scope="col">Edit</th>
                      <th scope="col">Delete</th>
                   </tr>
               </thead>
               <tbody>
                   {restaurants.map((restaurant)=>{
                       return (
                           <tr>
                               <td>{restaurant.name}</td>
                               <td>{restaurant.location}</td>
                               <td>{"$".repeat(restaurant.price_range)}</td>
                               <td>{restaurant.reviews}</td>
                               <td>
                               <button className="btn btn-warning">Update</button>
                               </td>
                               <td>
                               <button className="btn btn-danger">Delete</button> 
                               </td>
                               
                           </tr>
                       );                       
                         })}             
               </tbody>
            </table>
        </div>
    )
}
export default RestaurentList

API 输出:-

{
    "status": "Success",
    "results": 1,
    "data": {
        "restaurants": [
            {
                "id": "1",
                "name": "Mcdonalds",
                "location": "Hyderabad",
                "price_range": 3
            }
        ]
    }
}

这是我收到的错误。 在此处输入图片描述

3个回答

因此 response.data 是来自您的抓取工具(axios 可能)的对象。您需要像这样到达餐厅;

const response = await RestaurentFinder.get("/");
const restaurantResult = response.data;
setRestaurents(restaurantResult.data.restaurants);
hurricane
2021-09-29

restaurants 的初始值是什么?您的请求是异步的,但渲染不是。您需要等待数据被获取。一种方法是显示一些微调器:

const { restaurants, setRestaurents, loading, setLoading } =
  useContext(RestaurentsContext);

useEffect(async () => {
  const fetchData = async () => {
    setLoading(true);

    try {
      const response = await RestaurentFinder.get("/");

      setRestaurents(response.data.restaurants);
    } catch (err) {
    } finally {
      setLoading(false);
    }
  };
  fetchData();
}, []);

if (loading) {
  return <span>Loading...</span>
}

或者您可以为 restaurants 设置默认值 - [] 或者只检查未定义:

{restaurants?.map(/* ... */)}
Алексей Мартинкевич
2021-09-29

If you are using axios as HTTP module:

 const {response : { data : { restaurants } }} = await
    RestaurentFinder.get("/");
    setRestaurents(restaurants);

If You are using Fetch

 const response  = await RestaurentFinder.get("/");
 const {response : { data : { restaurants } }} = await response.json();
    setRestaurents(restaurants);
Muhammad Junaid Aziz
2021-09-29