[英]Fetching data from api promise in react API
我使用 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)
我在控制台中未定义。
如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))
该承诺仅在 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
您可以在 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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.