从react api中的api promise获取数据



我使用package.json.中的特定代理从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((数据时,它看起来像console:中的那样

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object

在[[PromiseResult]]里面有我需要处理的信息。比如:产品

我如何访问这些产品并在我的页面中循环它。求你了,我需要帮助。

因为当我访问这样的产品时:

console.log(products.data.products)

我在控制台中有未定义的。

如MDN:上传JSON数据中所述,从API接收数据后,应在单独的.then进程中处理每个操作。

fetch(apiLink, {
method: 'POST',
body: JSON.stringify({
"categories": [
"13", "14", "4", "8"
]
})
})
.then(response => response.json())
.then(data => console.log(data.products))

您可以在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]);

promise只在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))

您可以在以下位置了解更多关于承诺的信息:https://learnjsx.com/category/2/posts/es6-promise

最新更新