【发布时间】:2022-07-05 16:45:34
【问题描述】:
希望是一个简单的。
我在我的组件中进行 API 调用,它会记录一些帐户信息,例如 AccountUid、Category 等,我使用状态来设置这些信息。
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]);
这工作得很好,它在我的 .then 中记录正确的值。
然而,问题是我想将这些作为道具传递下去。但是我收到一个错误,它们被返回为 null(我的默认状态)。我假设它们正在向前跳跃。
<div className="App">
<GetAccountName
accountUID={accountDetails.accounts[0].accountUID}
defCategory={accountDetails.accounts[0].defaultCategory}
/>
</div>
如何将即时记录的 2 个详细信息作为道具传递?我已经尝试将默认状态设置为 "" 而不是 null 并且只是得到它是未定义的。
【问题讨论】:
-
仅当
accountDetails不为空时,您能否有条件地呈现您的子组件? -
好吧,我真的不希望它有条件地渲染。子组件将始终呈现我只是不介意在调用时传递的详细信息是否为空白 0.2 秒。
标签: javascript reactjs components state react-props