我有這個組件可以呈現喜歡這本書的人數,但是我無法在我的狀態下獲得一致的結果。
這是我的代碼:
///this is for getting the book details
const {id} = useParams();
const dispatch = useDispatch();
const[hasliked, sethasliked] = useState(null);
useEffect(() => {
const bookData = {
id: id
}
dispatch(openBook(bookData))
}, [])
///and this is for setting the state of the component
const { bookFeatured, isLoading, isSuccess, openbook, likeStatus } = useSelector(state => state.book);
const { user, isError, message } = useSelector(state => state.auth);
useEffect(()=>{
if(openbook.noOfLikes?.find((noOfLikes) => noOfLikes === user._id)){
sethasliked(true)
}else{
sethasliked(false)
}
},[openbook])
const Likes = () => {
return hasliked
? (
<><FaHeart fontSize="small" /> {hasliked.toString()}</>
) : (
<><FaRegHeart fontSize="small" fill='white'/> {hasliked.toString()}</>
);
};
這里的事情是我從 const hasliked 獲取值時得到不一致的結果,如果我已經喜歡一本書,它有時會告訴我 hasliked 是假的,但有時它會變為真,這導致我每個人都得到不同的結果當我渲染組件時,我認為這與由于異步操作導致的 useEffect 延遲有關,對此我能做些什么嗎?
uj5u.com熱心網友回復:
您是否嘗試過使用 setTimeout?
useEffect( () => {
const tmr = setTimeout( () => {
const bookData = { id: id }
dispatch( openBook(bookData) )
}, 500)
return () => clearTimeout(tmr);
}, [])
useEffect( () => {
const tmr = setTimeout( () => {
if (openbook.noOfLikes?.find( (noOfLikes) => noOfLikes === user._id) ) {
sethasliked(true)
} else { sethasliked( false) }
}, 500)
return () => clearTimeout(tmr);
},[openbook])
uj5u.com熱心網友回復:
- 您正在嘗試使用 a 呈現布林值
.toString()?為什么不做
return hasliked
? (
<><FaHeart fontSize="small" />True</>
看到hasliked那里已經是真的了。
- 這
else{
sethasliked(false)
}
可以通過將 init 更改為
const[hasliked, sethasliked] = useState(false);
- 如果您
dispatch(openBook(bookData))正在回傳一個承諾,您可以hasliked在一個.then塊中設定,從而消除對第二個使用效果的需要
- 從此改變回報
return hasliked
對此
return hasliked && openbook
uj5u.com熱心網友回復:
您可以將 a 添加loading state到您的組件并檢查加載狀態是true顯示加載程式還是顯示您的組件。
const {id} = useParams();
const dispatch = useDispatch();
const[hasliked, sethasliked] = useState(null);
const [loading, setLoading] = useState(false) // The loading state
useEffect(() => {
setLoading(true) // Setting the loading state true
const bookData = {
id: id
}
dispatch(openBook(bookData))
}, [])
///and this is for setting the state of the component
const { bookFeatured, isLoading, isSuccess, openbook, likeStatus } = useSelector(state => state.book);
const { user, isError, message } = useSelector(state => state.auth);
useEffect(()=>{
if(openbook.noOfLikes?.find((noOfLikes) => noOfLikes === user._id)){
sethasliked(true)
setLoading(false) // Setting loading state to false
}else{
sethasliked(false)
setLoading(false) // Setting loading state to false
}
},[openbook])
const Likes = () => {
// show a loader if loading is true
if(loading) {
return <div>Loading...</div>
}
return hasliked
? (
<><FaHeart fontSize="small" /> {hasliked.toString()}</>
) : (
<><FaRegHeart fontSize="small" fill='white'/> {hasliked.toString()}</>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476201.html
標籤:javascript 反应
