【问题标题】:items.map is not a function reactitems.map 不是函数反应
【发布时间】:2022-01-25 23:09:43
【问题描述】:

我在从我的 api 获取数据并将其显示在网页上时遇到问题。我收到此错误:“items.map 不是函数”。我不确定这是此代码的问题,还是我在 api 中获取请求的代码,我将发布这两个代码以防万一。

我将在下面粘贴我的代码,但没有指向我的 api 的链接。 谢谢,

import React from "react";

class App extends React.Component {


  constructor(props) {

    super(props);

    this.state = {
        items: [],
        isLoaded: false
    }

}

componentDidMount() {

  fetch(" api link ")
      .then(res => res.json())
      .then(json => {
        this.setState({ isLoaded: true, items: json });
      }).catch((err) => {
          console.log(err);
      });

}


render() {

  const { isLoaded, items } = this.state;

  if (!isLoaded)
      return <div>Loading...</div>;

  return (
      <div className="App">
          <ul>
              {items.map(item => (
                  <li key={item.oid}>
                      Name: {item.rows.productName} | Condition: {item.rows.productCondition}
                  </li>
              ))}
          </ul>
      </div>
  );

}

}

export default App;

API 代码:

async function getComments(req) {
   let status = 500, data = null;
   try {

         const sql = 'SELECT * FROM products';
         const rows = await db.query(sql);

         if (rows) {
            status = 200;
            data = {
                rows,

            };
         } else {
            status = 204;
         }
     
   } catch (e) {
      console.error(e);
   }
   return { status, data };
}


app.get('/demo/api_project', async (req, res) => {
   const { status, data } = await getComments(req);
   res.status(status);
   if (data) res.json(data);
   else res.end();
})

【问题讨论】:

  • 你的 api 的响应是什么?发布示例回复
  • 您的 API 响应是一个对象,而不是一个数组。看起来您应该将items 状态设置为json.rows 而不仅仅是json
  • @Vineesh 在我打开 api 链接时出现了什么?
  • 是的,如果它不是一个数组,您可能必须使用它或相应地格式化它@JakubK
  • @RobinZigmond 谢谢,天哪,我已经尝试了这么久。我认为当我在 item.productName 等中有 .rows 时它会起作用

标签: javascript reactjs api


【解决方案1】:

试试 console.log() 你从 api 得到的响应,你可能会发现你的数组嵌套在响应对象中。

【讨论】:

  • 这可能是一条评论
猜你喜欢
  • 2019-08-03
  • 2019-04-21
  • 2023-02-15
  • 2019-12-16
  • 2021-01-04
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多