Consider the following code using useIsFocused:

4 phương ánCó giải thíchDễ
Đề bài
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 án
Lờ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

Xuất hiện trong 1 bộ đề