如何循环遍历 Promise 的结果以将其传递给 React 组件
How to loop through results from a Promise to pass it to React components
我想这是因为我需要在 JS
中了解更多关于 Async
和 Promises
的知识
但是我有一些 Async API
和 returns 一些人的信息,在 Chrome 的控制台中显示的结构中有类似这样的信息。我复制了第一个人:
Promise {<fulfilled>: Array(12)}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(12)
0:
id: "ec6eee79-5ab8-44a9-8fbf-35668ec3a668"
name: "John Travolta"
__proto__: Object
所以我现在写了一个简单的组件来循环遍历它们,但显然这不是正确的方法。我不得不注释掉失败的部分。但这是我希望完成的事情。
那我应该怎么改呢?
const UserComponent = (props) => {
const results = API.getSomePeopleInfo().then((response) => {
const result = Promise.resolve(response.data);
console.log("so data was this: ", result);
});
return (
<div>
<h1>A user</h1>
{/*{results.map((r) => (*/}
{/* <li>{r.name}</li>*/}
{/*))}*/}
</div>
);
};
您正在使用异步函数,它不会立即解析,这意味着当您到达渲染方法时,结果将没有数据。您可以将其设为状态变量并在 then 回调中更新它:
import { useState } from 'react'
const UserComponent = (props) => {
// Using react with hooks
const [results, setResults] = useState([]);
API.getSomePeopleInfo().then((response) => {
const peoples = response.data;
setResults(peoples)
});
return (
<div>
<h1>A user</h1>
{/*{results && results.map((r) => (*/}
{/* <li>{r.name}</li>*/}
{/*))}*/}
</div>
);
};
我想这是因为我需要在 JS
中了解更多关于 Async
和 Promises
的知识
但是我有一些 Async API
和 returns 一些人的信息,在 Chrome 的控制台中显示的结构中有类似这样的信息。我复制了第一个人:
Promise {<fulfilled>: Array(12)}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(12)
0:
id: "ec6eee79-5ab8-44a9-8fbf-35668ec3a668"
name: "John Travolta"
__proto__: Object
所以我现在写了一个简单的组件来循环遍历它们,但显然这不是正确的方法。我不得不注释掉失败的部分。但这是我希望完成的事情。 那我应该怎么改呢?
const UserComponent = (props) => {
const results = API.getSomePeopleInfo().then((response) => {
const result = Promise.resolve(response.data);
console.log("so data was this: ", result);
});
return (
<div>
<h1>A user</h1>
{/*{results.map((r) => (*/}
{/* <li>{r.name}</li>*/}
{/*))}*/}
</div>
);
};
您正在使用异步函数,它不会立即解析,这意味着当您到达渲染方法时,结果将没有数据。您可以将其设为状态变量并在 then 回调中更新它:
import { useState } from 'react'
const UserComponent = (props) => {
// Using react with hooks
const [results, setResults] = useState([]);
API.getSomePeopleInfo().then((response) => {
const peoples = response.data;
setResults(peoples)
});
return (
<div>
<h1>A user</h1>
{/*{results && results.map((r) => (*/}
{/* <li>{r.name}</li>*/}
{/*))}*/}
</div>
);
};