我在一個組件中有以下代碼,我使用 cookie 值來決定要顯示哪個組件或 div 塊。
這最終按預期作業。但是有一段時間似乎尚未檢查 cookie 值。
在此期間,我一直先進入else街區。幾秒鐘后,我if正確輸入了該塊。
但為什么?那Cookies.get是一個異步呼叫。但我在里面呼叫它useEffect并使用等待。
請問我可以如何修改它,以便如果 cookie 存在,我將永遠不會進入 else 塊?
import React from 'react';
import Cookies from 'js-cookie';
const Sample = () => {
const [cookie, setCookie] = React.useState(false);
const hasCookie = async () => !!Cookies.get('my-cookie');
React.useEffect(() => {
const myCookie = async () => await hasCookie();
myCookie().then((result) => setCookie(result));
}, []);
const component = () => {
if (cookie) {
console.log(`YES there is a cookie: ${cookie}`);
return <div>
Yup the cookie exists
</div>;
} else {
console.log(`NO no cookie: ${cookie}`);
return <div>
Nope no cookie
</div>;
}
};
return component();
};
export default Sample;
作為參考,以下是控制臺日志,它在變為 true 之前列印 false 一段時間。
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:20 NO no cookie: false
Sample.jsx:15 YES there is a cookie: true
Sample.jsx:15 YES there is a cookie: true
Sample.jsx:15 YES there is a cookie: true
....
uj5u.com熱心網友回復:
那么首先有一些可能是未來的問題:
因為Cookies.get('my-cookie')回傳一個 Promise,所以它是一個物件。在物件上使用!!總是回傳 true(物件是真實的)。
所以hasCookie應該總是回傳true?
為了讓它正確地測驗它是否存在,你應該awaitPromise 直到它解決,然后!!在解決的值上使用:
!!(await Cookies.get('my-cookie'));
要回答您的問題,最常見的方法是跟蹤是否正在加載的狀態:
const [loading, setLoading] = useState(true);
加載時,您回傳其他內容:
if (loading) return null; // if you don't want to render anything
否則,您可以正常繼續。
設定 cookie 時,還要確保將 loading 設定為 false:
setCookie(result);
setLoading(false);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432991.html
標籤:javascript 反应
