返回屏幕时,React Native中未调用useEffect

时间:2020-02-12 07:12:43

标签: reactjs react-native use-effect

你好吗。 这是此问题的方案。 假设有两个简单的屏幕。

  1. 进入一个屏幕。屏幕的useEffect。
  2. 从A屏幕导航到B屏幕
  3. 从B导航回A屏幕。 目前,尚未调用useEffect。

    function CompanyComponent(props) {
    
       const [roleID, setRoleID] = useState(props.user.SELECTED_ROLE.id)
    
       useEffect(()=>{ 
    
     // this called only once when A screen(this component) loaded,  
     // but when comeback to this screen, it doesn't called
       setRoleID(props.user.SELECTED_ROLE.id)
     }, [props.user])
    }
    

因此,当再次返回到A屏幕(不从道具加载)时,屏幕A的更新状态保持不变

我没有在屏幕B中更改props.user。 但是我认为const [roleID, setRoleID] = useState(props.user.SELECTED_ROLE.id)这行至少应该被调用。

我正在使用redux-persist。我认为这不是问题。 对于导航,我使用此

// to go first screen A, screen B
function navigate(routeName, params) {
    _navigator.dispatch(
        NavigationActions.navigate({
            routeName,
            params,
        })
    );
}
// when come back to screen A from B
function goBack() {
    _navigator.dispatch(
        NavigationActions.back()
    );
}

当屏幕出现时,我可以使用任何回调吗? 我的代码有什么问题?

谢谢

4 个答案:

答案 0 :(得分:28)

以下解决方案对我有用:

import React, { useEffect } from "react";
import { useIsFocused } from "@react-navigation/native";

const ExampleScreen = (props) => {
    const isFocused = useIsFocused();

    useEffect(() => {
        console.log("called");
        getInitialData();
    }, [props, isFocused]);

    const getInitialData = async () => {}    

    return (
        ......
        ......
    )
}

我已经使用了反应导航5 +

@ react-navigation / native”:“ 5.6.1”

答案 1 :(得分:9)

从A导航到B时,组件A不会被破坏(它留在导航堆栈中)。因此,当您向后浏览时,该代码不会再次运行。

也许是一种更好的方式来实现要使用导航生命周期事件的条件(我假设您正在使用react-navigation),即订阅didFocus事件并在组件集中时运行所需的任何代码,例如

const unsubscribe = props.navigation.addListener('didFocus', () => {
    console.log('focussed');
});

别忘了在适当的时候退订

// sometime later perhaps when the component is unmounted call the function returned from addListener. In this case it was called unsubscribe
unsubscribe();

答案 2 :(得分:2)

当前版本的 React Navigation 提供了 useFocusEffect 钩子。见here

答案 3 :(得分:1)

React Navigation 5 提供了一个 useFocusEffect 钩子,类似于 useEffect,唯一的区别是它只在当前屏幕聚焦时运行。检查文档 https://reactnavigation.org/docs/use-focus-effect

 useFocusEffect(
    useCallback(() => {
      const unsubscribe = setRoleID(props.user.SELECTED_ROLE.id)
      return () => unsubscribe()
    }, [props.user])
  )