React Prop返回零,因为它依赖于状态
希望只是一个。
我在我的组件中进行了一个API调用,其中带来了一些帐户信息,例如AccountUID,类别等,我使用状态设置这些信息。
useEffect(() => {
fetch(feed_url, {
headers: {
//Headers for avoiding CORS Error and Auth Token in a secure payload
"Access-Control-Allow-Origin": "*",
Authorization: process.env.REACT_APP_AUTH_TOKEN,
},
})
//Return JSON if the Response is recieved
.then((response) => {
if (response.ok) {
return response.json();
}
throw response;
})
//Set the Account Name state to the JSON data recieved
.then((accountDetails) => {
setAccountDetails(accountDetails);
console.log(accountDetails.accounts[0].accountUid);
console.log(accountDetails.accounts[0].defaultCategory);
})
//Log and Error Message if there is an issue in the Request
.catch((error) => {
console.error("Error fetching Transaction data: ", error);
});
}, [feed_url]);
这效果很好,并且在测试时记录了我的正确值。
但是,问题是我想将其作为道具传递。但是我遇到了一个错误,因为它们被返回为null(我的默认状态)。我想,他们跳下来。
<div className="App">
<GetAccountName
accountUID={accountDetails.accounts[0].accountUID}
defCategory={accountDetails.accounts[0].defaultCategory}
/>
</div>
我如何通过“道具”记录的两个细节来传递?我已经尝试将默认状态设置为“”而不是null,而只是确定它是未定义的。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不想在孩子组件中使用有条件渲染,因此应尝试可选的链接
If you dont want to use conditional render in your child component, so you should try optional chaining
由于提取是异步的,因此最常见的方法是显示一些负载指示器(例如旋转器)&amp;数据进来后,请改用组件。
如果您不需要指标,则可能只需返回
null
。一般的想法是根据承诺状态操纵某些中间状态(例如
data
iSerror )。查看或更轻的抽象(例如
usefetch
hook 查看它们如何管理。这是
usefetch
的示例实现>::Since fetching is asyncronous, the most common way is to show some loading indicator (like a spinner) & once the data come in, show the component instead.
If you don't need an indicator, you might just return
null
.The general idea is to manipulate some intermediary states (e.g.
data
,isError
) based on the promise state.Check out
react-query
library example or a lighter abstraction likeuseFetch
hook to see how they manage it.Here's a sample implementation of
useFetch
taken from this article: