我有一個螢屏呼叫 api 來獲取一些資料,然后顯示
我看到的一個問題是,當我離開螢屏(我使用的是 react-navigation 6.x)然后回傳它時useEffect()不會被呼叫
從我到目前為止所閱讀的內容來看,這取決于userId不改變的價值(我認為我需要圍繞useEffect()鉤子做更多的閱讀才能更好地理解,也許有人會幫助解決這個問題)
import React, {useState, useEffect, useContext} from 'react';
import AppContext from '../../components/AppContext.js';
export const CreateNewEvent = () => {
const globalContext = useContext(AppContext);
const userId = globalContext.userInfo.id;
useEffect(() => {
const body = JSON.stringify({userId});
fetch(eventTypesUrl, {
method: 'POST',
headers: {'Content-Type': 'application/json', Accept: 'application/json'},
body: body,
})
.then(response => response.json())
.then(json => setEventTypeData(json))
.catch(error => console.error(error))
.finally(() => setLoading(false));
}, [userId]);
}
所以在我的場景中,我在螢屏 1 上(在這里我可以創建一個事件,請求獲取所有事件型別并將它們加載到選擇選單中)
當我導航到螢屏 2(以創建事件型別)然后回傳螢屏 1 時,useEffect()不會呼叫掛鉤導致無法看到我剛剛創建的事件型別(希望這是有道理的).. 還請注意,任何之前在螢屏 1 中輸入的資料仍然保留
我遇到了這篇似乎是我正在處理的帖子,只是有點不確定如何使用我的設定來實作
當我回傳時,如何確保 Screen 2 進行 api 呼叫并且清除所有以前的表單資料?
謝謝
uj5u.com熱心網友回復:
React Navigation 的核心是在用戶導航回該螢屏以進行性能優化時不會重新渲染螢屏,并避免不必要的重新渲染。
當需要時,它們提供了一個有用的鉤子來檢測螢屏何時聚焦并運行一些副作用。
讓我們重構代碼如下:
Top-level import
import { useFocusEffect } from "@react-navigation/core";
// Run side effects when screen focused, navigated, or visited
useFocusEffect(
React.useCallback(() => {
const body = JSON.stringify({userId});
fetch(eventTypesUrl, {
method: 'POST',
headers: {'Content-Type': 'application/json', Accept: 'application/json'},
body: body,
})
.then(response => response.json())
.then(json => setEventTypeData(json))
.catch(error => console.error(error))
.finally(() => setLoading(false));
return () => {
// Run somelogisx when user leave screen,
// Cleaning caches or cancelling subscriptions
};
}, [userId]))
注意: React.useCallback是useFocusEffectAPI 的一部分。React Navigation 團隊試圖通過 memoization 優化螢屏性能。
uj5u.com熱心網友回復:
在 React Native 中,當您向前導航時,每個螢屏都會被推送到導航堆疊。
現在,當您向后導航時,會彈出前一個螢屏并顯示堆疊中最頂層的螢屏。由于最上面的螢屏中沒有任何東西(狀態或道具)發生變化,因此不會重新渲染。
所以你必須做一些手工作業。
import { useIsFocused } from "@react-navigation/native";
const isFocused = useIsFocused();
isFocused 是布林值
useEffect(() => {
if (userId && isFocused) {
// Code which you want to execute when screen is loaded first
// time(and after userId is initialised) or loaded after press of
// back button
}
}, [userId, isFocused]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405735.html
標籤:
上一篇:在輸入欄位中將defaultValue和value一起反應
下一篇:何時使用React錯誤邊界組件?
