我試圖從 API 中獲取陣列中的專案串列,但是當我在專案上使用 map 函式時,它說 map 不是函式。
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
uj5u.com熱心網友回復:
你不應該使用JSON.stringify. 因為它已經是物件
只需將其更改為以下代碼
const response = await axios.get('http://localhost:5000/api/products');
setItems(response.data);
uj5u.com熱心網友回復:
axios.get()方法回傳object并且您不能map()在物件上使用該方法,因為它是在prototype陣列的 上定義的。您可以在此處找到更多詳細資訊Array.prototype.map()
首先,讓我們了解什么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: {}
}
您可以在此處找到更多詳細資訊。這意味著您要查找的實際資料位于response.data. 你需要提取它。
const { data } = response;
現在您需要分析并處理data成React可渲染格式。
uj5u.com熱心網友回復:
它由 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363166.html
標籤:javascript 反应 字典
