Muat Ulang Layar di goBack react native

Aug 26 2020

Mari kita asumsikan ada dua layar di navigator tumpukan:

Layar_pertama -> Layar_Kedua

Bagaimana kita bisa menyegarkan / memuat ulang layar sebelumnya ketika kembali ke layar itu dengan memanggil this.props.navigation.goBack ()?

Saya menggunakan versi react-native dan react-navigation di bawah ini:

"react-native": "0.63.2",
"@react-navigation/native": "^5.7.3",
"@react-navigation/stack": "^5.9.0",

Saya sudah mencoba di bawah ini,

componentDidMount() {
    this.props.fetchData();
    this.willFocusSubscription = this.props.navigation.addListener(
      'willFocus',
      () => {
        this.props.fetchData();
      }
    );
  }

  componentWillUnmount() {
    this.willFocusSubscription.remove();
  }

Namun tidak mendapatkan hasil yang diharapkan.

Jawaban

1 rishikesh_07 Aug 27 2020 at 01:25

coba ini akan berhasil

  componentDidMount() {
    this.onFocusCall = this.props.navigation.addListener('willFocus', () => {
      this.apiCall();
    });
  }
  componentWillUnmount() {
    this.onFocusCall.remove();
  }
1 SaachiTech Aug 27 2020 at 06:04

Karena Anda menggunakan react-navigation 5x, Anda perlu memperbarui listener untuk mengikuti

componentDidMount() {
    this.props.fetchData();
    this.willFocusSubscription = this.props.navigation.addListener(
      'focus',
      () => {
        this.props.fetchData();
      }
    );
  }

dokumen: https://reactnavigation.org/docs/function-after-focusing-screen/

1 ParthNavadiya Oct 28 2020 at 06:21

Coba yang ini, ini berfungsi dengan baik

  useEffect(() => {
      const unsubscribe = navigation.addListener("focus", async () => {
      const response = await apiCall();
    });

      return unsubscribe;
    }, [navigation]);