【问题标题】:JavaScript's map() method is failing with the error "map is not a function"JavaScript 的 map() 方法因错误“map is not a function”而失败
【发布时间】:2021-11-19 08:15:44
【问题描述】:

我试图从 API 的数组中获取项目列表,但是当我在项目上使用地图函数时,它说地图不是函数。

import React from 'react'
import { useState } from 'react';
const axios = require('axios');

const Api = () => {

const [items, setItems] = useState([]);

   const getUser = async () => {
        try {
          const response = await axios.get('http://localhost:5000/api/products');
          console.log(response);
          setItems (JSON.stringify(response));
        } catch (error) {
          console.error(error);
        }
      
}

return (
    <div>
        <button onClick={getUser}> Fetch Data</button>
        <br />
        <br />
        <br />
        {items}
    </div>
)

}

export default Api

【问题讨论】:

  • 什么是setItems?为什么使用JSON.stringfy() 而不是JSON.parse()
  • axios 通常以response.data 的形式返回数据(并解析)。因此,请尝试将其添加到您的状态。并且不要对数据进行字符串化。你为什么这样做?
  • 你有JSON.stringify()你的数据,这使它成为一个字符串,array#map没有在字符串上定义。您需要访问response.data 并检查它是否为数组,然后使用数组函数对其进行迭代。
  • 我试过 setItems(response.data);但它说 × 错误:对象作为 React 子对象无效(找到:带有键 {_id、name、price、imageUrl、__v} 的对象)。如果您打算渲染一组子项,请改用数组。

标签: javascript reactjs dictionary


【解决方案1】:

您不应该使用JSON.stringify。因为它已经是对象了

只要改成下面的代码


  const response = await axios.get('http://localhost:5000/api/products');
  setItems(response.data);

【讨论】:

  • 我试过 console.log(typeof response.data);它说它是一个对象。那么,我该怎么办?
  • Console.log 输出并更新您希望从 response.data 呈现哪些数据的答案
【解决方案2】:

axios.get() 方法返回 object 并且您不能在对象上使用 map() 方法,因为它已在数组的 prototype 上定义。您可以找到Array.prototype.map()here的更多详细信息

首先,让我们了解axios.get()方法返回什么。

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

您可以找到更多详细信息here。这意味着您要查找的实际数据位于response.data 中。您需要提取它。

const { data } = response;

现在您需要将data 分析并处理成React 可渲染格式。

【讨论】:

    【解决方案3】:

    它由 setItems(response.data) 工作

    import React from 'react'
    import { useState } from 'react';
    const axios = require('axios');
    
    const Api = () => {
    
    const [items, setItems] = useState([]);
    
       const getItems = async () => {
            try {
              const response = await axios.get('http://localhost:5000/api/products');
              console.log(response.data);
              
              setItems (response.data);
             
              console.log(response.data)
            } catch (error) {
              console.error(error);
            }
            
    }
    
    return (
        <div>
            <button onClick={getItems}> Fetch Data</button>
            <br />
            <br />
            <br />
           
            {items.map((item)=>(
                <div >
                    <h1>{item.name}</h1>
                    <h2>{item.price}</h2>
                </div>
            ))}
    
    
        </div>
    )
    

    }

    export default Api
    

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      相关资源
      最近更新 更多