TypeError: food.map is not a function in Reactjs

TypeError: food.map is not a function in Reactjs

我是 Reactjs 新手。我正在使用 React hooks 和 axios 从其 id 中获取 单个 post 数据的 api。我调用了 api 并通过扩展运算符使用 props 将数据传递给子组件。服务器运行但在页面上呈现上述错误。我已经正确使用了 map 函数,但它说 map 不是函数。我在线检查了问题,有类似问题的用户说数据可能不是数组。它应该是一个数组,但在我的例子中是不同的数据类型,如 id、name、title、price 等。

我的FoodPage.js

function Food() {

  const [food, setFood] = useState([])
  const [id,setId] = useState(1)

  useEffect(() => {
    axios.get(`https://exampleurl.herokuapp.com/api/menus/${id}`)
    .then(abc=>{
      console.log(abc.data)
      setFood(abc.data)
    })
    .catch(err =>{
      console.log(err) 
    })
  }, [])


 return (
  <div>
    <div className="food-page">         
         {food.map((foodItem) => {
            return <PageHeader  {...foodItem} key={foodItem.id} />;
          })}
           <Customize />
          {food.map((foodItem) => {
            return <FoodDescription  {...foodItem} key={foodItem.id} />;
          })}       
    </div>
  </div>
  );
}

export default Food;

我的食物描述:

function FoodDescription(props) {

  console.log(props);
  const {food_name,long_title,subtitle,description,price,id} = props;

  return (
    <div className="food-description">
        <div className="container">
          <div className="title">
            <div className="main-title">{food_name}</div>
          </div>
          <div className="description">
            {/* {description.map((des: string, index: number) => { */}
            {description.map((des, index) => {  
              return <p key={index}>{des}</p>;
            })}
          </div>
          <div className="order">
            <div className="quantity">
              <div className="negative" onClick={() => this.handleDecrement()}>
                -
              </div>
              {this.state.quantity}
              <div className="positive" onClick={() => this.handleIncrement()}>
                +
              </div>
            </div>
            <ExploreButton active="link-active">
              Add to Order -{price}
            </ExploreButton>
          </div>
        </div>
      </div>
  )
}

export default FoodDescription;

更新

控制台中的 abc.data 给出以下内容:

根据你的API结果,当你调用

https://texas-crm1.herokuapp.com/api/menus/1 它 return 一个对象,而不是一个数组。

{
    "id": 1,
    "category": "main courses",
    "image": "imgUrl",
    "image_url": "imgUrl",
    "food_name": "butter chicken",
    "subtitle": null,
    "long_title": null,
    "description": "<p>this is a test data from backend for butter chicken in main courses.</p>",
    "price": 49.0,
    "rating": 3.0
}

所以你不需要映射食物试试这个:

function Food() {

  const [food, setFood] = useState([])
  const [id,setId] = useState(1)

  useEffect(() => {
    axios.get(`https://texas-crm1.herokuapp.com/api/menus/${id}`)
    .then(abc=>{
      console.log(abc.data)
      setFood(abc.data)
    })
    .catch(err =>{
      console.log(err) 
    })
  }, [])


 return (
  <div>
    <div className="food-page">         
       <PageHeader  {...food} key={food.id} />;
       <Customize />
       <FoodDescription  {...food} key={food.id} />;
    </div>
  </div>
  );
}

export default Food;

如果catch没有报错,说明你对服务器的请求是正确的,但是超时需要显示加载器

if (!food?.length) return <div>Loading </div>    
return (
      <div>
        <div className="food-page">         
             {food?.map((foodItem) => {
                return <PageHeader  {...foodItem} key={foodItem.id} />;
              })}
               <Customize />
              {food?.map((foodItem) => {
                return <FoodDescription  {...foodItem} key={foodItem.id} />;
              })}       
        </div>
      </div>
      );
    }

您正在调用一个端点,其中 return 一项不是食物列表,我猜它类似于“GetById”, 这是一个对象(一种食物):

{
    "id": 1,
    "category": "main courses",
    "image": "imgUrl",
    "image_url": "imgUrl",
    "food_name": "butter chicken",
    "subtitle": null,
    "long_title": null,
    "description": "<p>this is a test data from backend for butter chicken in main courses.</p>",
    "price": 49.0,
    "rating": 3.0
}
此代码可以工作,但您应该保留您的代码并将端点更改为(如果存在)“https://texas-crm1.herokuapp.com/api/menus/

useEffect(() => {
    axios.get(`https://texas-crm1.herokuapp.com/api/menus/${id}`)
    .then(abc=>{
      console.log(abc.data)
let arr=[abc.data]
      setFood(prev=>arr)
    })
    .catch(err =>{
      console.log(err) 
    })
  }, [])