我是 React 的新手,我很難弄清楚如何在獲取資料之前等待狀態進行特定(非空)更新。我正在使用firebase JWT并將令牌傳遞到標頭中,但是使用我當前的代碼運行并傳遞了null值。是否有一個漂亮的鉤子技巧來確保我的 fetchData 函式只運行一次并且只在設定令牌值之后運行?
我嘗試將狀態設定為, const [token, setToken] = useState(auth.currentUser.getIdToken());但它似乎將承諾回傳到標頭而不是令牌中(猜測它是因為它是異步的)。謝謝!
import React, { useState, useEffect } from 'react';
import { auth } from '../../firebase-config';
const RecordEntry = (props) => {
const [token, setToken] = useState();
const [isLoading, setIsLoading] = useState(false);
var mydata =
{
entry_id = props.entry_id
}
//should only call this once
const fetchData = async () => {
const current_token = auth.currentUser.getIdToken();
setToken(current_token);
//need to yield here to verify token is set and not null - this is where I am stuck
fetch('https://mysite/api/recordEntry' , {
method: 'POST',
headers: new Headers({
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
}),
body: JSON.stringify(mydata)
})
.then((response) => response.json())
.then((data) => {
setIsLoading(false);
})
.catch((error) => {
setIsLoading(false);
console.log(error);
});
};
//passing empty array so the effect only runs once
useEffect(() => {
fetchData();
}, []);
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
<h1> Entry Recorded </h1>
</div>
);
};
export default RecordEntry;
uj5u.com熱心網友回復:
試試這個解決方案
const [didFetch,setDidFetch] = useState(false)
useEffect(() => {
if(!didFetch){
setDidFetch(true)
fetchData();
}
}, []);
uj5u.com熱心網友回復:
“感謝您的回復,我嘗試了此解決方案,但令牌仍未更新。標題顯示它是一個承諾物件,而不是預期的令牌字串。令牌本質上仍在等待更新。我需要一種暫停資料的方法直到令牌被填滿。”
所以試試這個:
const [token, setToken] = useState(null);
和
useEffect(() => {
if (token != null) fetchData();
}, [token]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410589.html
標籤:
