我使用 package.json 中的特定代理從 Company API 獲取資料。
這是我的代碼:
const [products, setProducts] = useState({
loading: false,
data: null,
error: false,
});
const apiLink = 'https://example.com/api/checkout/products/';
useEffect(() => {
setProducts({
loading: true,
data: null,
error: false,
});
fetch(apiLink, {
method: 'POST',
body: JSON.stringify({
"categories": [
"13", "14", "4", "8"
]
})
})
.then(response => {
response.json().then(data => console.log(data.products))
})
}, [apiLink])
但是當我 console.log() 資料在控制臺中看起來像這樣:
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
在 [[PromiseResult]] 里面有我需要處理的資訊。喜歡:產品
我怎樣才能訪問這個產品并在我的頁面中回圈它。請我需要幫助。
因為當我訪問這樣的產品時:
console.log(products.data.products)
我在控制臺中未定義。
uj5u.com熱心網友回復:
如MDN: Uploading JSON data 中所述,從 API 接收資料后,您應該在單獨的.then行程中處理每個操作。
fetch(apiLink, {
method: 'POST',
body: JSON.stringify({
"categories": [
"13", "14", "4", "8"
]
})
})
.then(response => response.json())
.then(data => console.log(data.products))
uj5u.com熱心網友回復:
該承諾僅在 fetch() 方法中需要,因為它是一個延遲計算,之后您可以使用任何方法來處理您的資料
fetch(apiLink, {
method: 'POST',
body: JSON.stringify({
"categories": [
"13", "14", "4", "8"
]
})
})
.then(response => response.json())
.catch(x=>console.log(x)).map(x=>console.log(x.products))
您可以在以下位置了解有關 Promise 的更多資訊:https : //learnjsx.com/category/2/posts/es6-promise
uj5u.com熱心網友回復:
您可以在 useEffect 中使用 async/await
useEffect(() => {
const init = async () => {
setProducts({
loading: true,
data: null,
error: false,
});
try {
const response = await fetch(apiLink, {
method: "POST",
body: JSON.stringify({
categories: ["13", "14", "4", "8"],
}),
});
response = await response.json();
// set your state after this
} catch (e) {
console.error(e);
}
};
init();
}, [apiLink]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352867.html
標籤:javascript 反应 接口
下一篇:具有固定位置和css屬性“animation”的div,當我動態添加類時,它不會使用“transform:translateY(0%)”屬性進行影片處理
