Consider the following component using useIsFocused and useEffect. What will be the behavior if the component is initially unfocused and then gets focused?
4 phương ánCó giải thíchKhó
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á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: "It will log 'ProfileScreen is now focused' every time the component gains focus". useIsFocused trả về true khi màn hình đang được hiển thị và false khi người dùng chuyển sang màn khác, đồng thời làm component render lại mỗi khi giá trị đổi. useEffect có mảng phụ thuộc chỉ gồm isFocused nên chỉ chạy lúc mount và khi isFocused thay đổi. Lần theo mã: lúc đầu chưa focus, isFocused là false, effect chạy nhưng điều kiện if không thoả nên không in gì; khi màn hình được focus, isFocused chuyển thành true, effect chạy lại và in dòng log; rời đi rồi quay lại thì chu trình lặp lại, nên log xuất hiện mỗi lần màn hình nhận focus. "It will log 'ProfileScreen is now focused' every time the component is rendered" sai vì effect không chạy theo mỗi lần render mà theo thay đổi của isFocused. "It will log 'ProfileScreen is now focused' only once when the component mounts" sai vì lúc mount màn hình chưa focus nên không in, và về sau còn in nhiều lần. "It will log 'ProfileScreen is now focused' every time the component is unfocused" sai vì khi mất focus isFocused là false, điều kiện if chặn việc in.
Cùng chương 5
In React Navigation, which hook should you use to get access to route parameters inside a functional component?Có lời giảiCâu hỏiWhich of the following hooks can you use to perform an action only when the screen is first mounted in React Navigation?Có lời giảiCâu hỏiWhich hook would you use to get access to the navigation object within a functional component in React Navigation?Có lời giảiCâu hỏiCả 24 câu của chủ đề24 câu