[英]How to prevent unnecessary API call in React useEffect?
我的HomeScreen
組件包含一個 API 調用來獲取當前用戶。 有沒有辦法讓它僅在用戶更改時進行 API 調用。 到目前為止,如果我離開屏幕然后回來,它會進行 API 調用並顯示加載程序,我認為這不是完美的用戶體驗,更不用說 API 請求是完全多余的,因為用戶沒有改變。
useEffect(() => {
dispatch(userRequest({ userId, userRole }))
}, [dispatch, userId, userRole])
我還試圖用reselect
,以獲得userId
和userRole
從Redux
和包裝我的HomeScreen
中的組件React.memo
但似乎得到重新呈現每一次
這是我從Redux
獲取數據的方法
const userId = useSelector(selectUserId)
const userRole = useSelector(selectUserRole)
我的選擇器:
const loginInfoSelector = (state: AppStateType) => state.loginInfo
export const selectUserId = createSelector(
loginInfoSelector,
(loginInfo) => loginInfo.id
)
export const selectUserRole = createSelector(
loginInfoSelector,
(loginInfo) => loginInfo.role
)
我會嘗試從依賴數組中刪除dispatch
為:
useEffect(() => {
dispatch(userRequest({ userId, userRole }))
}, [userId, userRole])
這樣它只會在userId
或userRole
發生變化時觸發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.