Which of the following hooks can replace manually registering an event listener to handle when a screen is focused?
4 phương ánCó giải thích
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "useFocusEffect". Trong React Navigation, thay vì tự đăng ký navigation.addListener với sự kiện focus bên trong useEffect rồi nhớ huỷ đăng ký, ta dùng useFocusEffect: nó chạy callback mỗi khi màn hình được focus và gọi hàm cleanup mà callback trả về khi màn hình mất focus; callback nên bọc trong useCallback để không chạy lại thừa. "useRoute" chỉ trả về đối tượng route hiện tại với name và params, không phản ứng với sự kiện focus. "useIsFocused" trả về giá trị boolean cho biết màn hình có đang được focus và làm component render lại khi giá trị đổi; nó hợp để hiển thị theo trạng thái nhưng không phải nơi chạy side effect thay cho listener. "useNavigationState" đọc một phần trạng thái của navigator, chẳng hạn số route trong ngăn xếp, không xử lý sự kiện focus.
Cùng chương 5
Consider the following component using useIsFocused and useEffect. What will be the behavior if the component is initially unfocused and then gets focused?
import React, { useEffect } from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';
function ProfileScreen() {
const isFocused = useIsFocused();
useEffect(() => {
if (isFocused) {
console.log('ProfileScreen is now focused');
}
}, [isFocused]);
return <Text>Profile Screen</Text>;
}Có lời giảiCâu hỏiWith hook in React Navigation, what will happen if you call useFocusEffect inside a functional component but provide an empty dependency array?Có lời giảiCâu hỏiIn React Navigation, which hook should you use to get access to route parameters inside a functional component?Có lời giảiCâu hỏiCả 24 câu của chủ đề24 câu