Consider the following code using useIsFocused:
4 phương ánCó giải thíchDễ
import React, { useEffect } from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';
function HomeScreen() {
const isFocused = useIsFocused();
useEffect(() => {
if (isFocused) {
console.log('HomeScreen is focused');
} else {
console.log('HomeScreen is not focused');
}
}, [isFocused]);
return <Text>Home Screen</Text>;
}What will be logged if the component is initially focused and then loses focus?
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: "'HomeScreen is focused' initially, followed by 'HomeScreen is not focused'". Lần theo mã: useIsFocused trả về true khi màn hình đang focus và gây render lại mỗi khi trạng thái này đổi; useEffect phụ thuộc [isFocused] nên chạy sau lần render đầu và chạy lại mỗi lần isFocused đổi giá trị. Ban đầu isFocused là true nên in ra HomeScreen is focused; khi người dùng chuyển sang màn hình khác, isFocused thành false, effect chạy lại và in ra HomeScreen is not focused. "'HomeScreen is focused' only" sai vì bỏ qua lần chạy lại khi mất focus. "'HomeScreen is not focused' only" sai vì lần đầu màn hình đang focus. "'HomeScreen is not focused' initially, followed by 'HomeScreen is focused'" đảo ngược thứ tự thực tế.
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