螢幕焦點更換時叫用函數
在本指南中,我們將呼叫一個函式或在螢幕對焦時重新整理畫面。這對於在使用者重新瀏覽分頁導覽器中的特定畫面時進行其他 API 呼叫,或追蹤他們在應用程式中點選的使用者事件會很有用。
我們有許多方法可用
- 使用事件聆聽器聆聽
'focus'
事件。 - 使用 react-navigation 提供的
useFocusEffect
勾子。 - 使用 react-navigation 提供的
useIsFocused
勾子。
觸發帶有 'focus'
事件聆聽器的動作
我們也可以使用事件聆聽器聆聽'focus'
事件。在設定事件聆聽器後,當畫面卸載時,我們也必須停止聆聽該事件。
使用這種方法,我們只能在畫面取得焦點時呼叫動作。這對於執行動作,例如為分析記錄畫面檢視,很有用。
範例
import * as React from 'react';
import { View } from 'react-native';
function ProfileScreen({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// The screen is focused
// Call any action
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
return <View />;
}
查看導覽事件指南以取得有關事件聆聽器 API 的更多詳細資訊。
在大部分情況下,建議使用 `useFocusEffect` 掛勾,而不是手動新增聆聽器。詳情請見下列說明。
使用 `useFocusEffect` 掛勾觸發動作
React Navigation 提供了一個掛勾,當畫面取得焦點時執行一個效應,而且當它失去焦點時清除它。這對於新增事件聆聽器、在畫面取得焦點時使用 API 呼叫擷取資料,或任何需要在畫面顯示後執行的動作,都很有用。
當我們試著在頁面失去焦點時停止某件事時,這特別方便,例如停止播放影片或音訊檔,或停止追蹤使用者的位置。
import { useFocusEffect } from '@react-navigation/native';
function Profile({ userId }) {
const [user, setUser] = React.useState(null);
useFocusEffect(
React.useCallback(() => {
const unsubscribe = API.subscribe(userId, (user) => setUser(data));
return () => unsubscribe();
}, [userId])
);
return <ProfileContent user={user} />;
}
請查看useFocusEffect
文件,以取得更多詳細資訊。
使用 `useIsFocused` 掛勾重新呈現畫面
React Navigation 提供了一個掛勾,用來傳回一個布林值,顯示畫面是否有焦點。
當畫面取得焦點時,這個掛勾將傳回 `true`;當我們的組件不再取得焦點時,傳回 `false`。這讓我們能夠依照使用者是否在畫面中,有條件地呈現一些東西。
當我們將焦點對焦及移開畫面時,`useIsFocused` 掛勾將會導致我們的組件重新呈現。使用這個掛勾組件可能會引發不必要的組件重新呈現,因為畫面會進入及離開焦點。這可能會造成問題,具體取決於我們在對焦時呼叫的動作類型。因此,我們建議僅在需要觸發重新呈現時使用這個掛勾。對於訂閱事件或擷取資料等副作用,請使用上述說明的方法。
import * as React from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';
function Profile() {
// This hook returns `true` if the screen is focused, `false` otherwise
const isFocused = useIsFocused();
return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}
這個範例也記錄在useIsFocused
API 文件中。