尝试在动态渲染操作中调用数据时,数组映射给我一个错误
function UserTransactionsComponent1() {
const [accounts, setAccounts] = useState();
useEffect(() => {
async function fetchData() {
const res = await fetch(
'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
);
const { data } = await res.json();
setAccounts(data);
}
fetchData();
}, []);
accounts.map((result) => {
const { account } = result;
});
return <PageLayout>Hi! {account}</PageLayout>;
}
export default UserTransactionsComponent1;
我在映射它之前 console.log(accounts) ,并且所有属性都在那里。问题是 acounts.map 中的 account 在 VSCode 上显示为灰色。它不会在退货时被取走。这导致我收到以下错误:TypeError:无法读取未定义的属性(读取“地图”)。这是什么原因呢?
function UserTransactionsComponent1() {
const [accounts, setAccounts] = useState();
useEffect(() => {
async function fetchData() {
const res = await fetch(
'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
);
const { data } = await res.json();
setAccounts(data);
}
fetchData();
}, []);
accounts.map((result) => {
const { account } = result;
});
return <PageLayout>Hi! {account}</PageLayout>;
}
export default UserTransactionsComponent1;
I console.log(accounts) right before I map it and all the properties are there. The issue is that the account in the acounts.map is showing greyed out on VSCode. It's not being picked up on the return. This is causing me to receive the following error: TypeError: Cannot read properties of undefined (reading 'map'). What's the reason for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
return 语句位于变量(帐户)范围之外。
The return statement is outside the variable (account) scope.
问题是您的映射函数在提取完成之前运行,因此当您尝试映射时帐户仍然未定义。
有几种方法可以解决这个问题。一种选择是仅使用 .then()。因此,请将您的地图函数放在 .then 中,即 useEffect 中。
这告诉代码仅在获取完成后才运行映射函数
The problem is that your map function is running before your fetch has completed, so accounts is still undefined when you try mapping.
There's a few ways to solve this. One options is just to use .then(). So put your map function inside of .then, inside your useEffect.
This tells the code to run the map function only after the fetch completes
accounts
在获取完成之前才定义,因此您需要将其映射到一个效果中,该效果等待设置accounts
的状态:最重要的是,当您返回时,
account
将为undefined
。您可以在获取数据时创建加载屏幕或其他内容,然后使用数据重新渲染:我不确定您要在地图函数中做什么;您没有具体指定您想要数组中的哪个帐户;你需要另一个状态。
accounts
is not defined until the fetch is complete, so you need to map it in an effect, which waits for the state ofaccounts
to be set:On top of that, when you return,
account
will beundefined
. You can create a loading screen or something while the data is fetching, then re-render with the data:I'm not sure what you're trying to do in your map function; you're not specifying specifically which account in the array you want; you'll need another state.