返回屏幕时未在 React Native 中调用 useEffect [英] useEffect not called in React Native when back to screen

查看:36
本文介绍了返回屏幕时未在 React Native 中调用 useEffect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好吗.这是这个问题的场景.假设有 2 个屏幕可以简化操作.

How are you. This is scenario of this issue. Let's say there are 2 screens to make it simple.

  1. 进入A画面.调用 A 屏幕的 useEffect.
  2. 从 A 屏幕导航到 B 屏幕
  3. 从 B 导航回 A 屏幕.此时不调用useEffect.

  1. enter A screen. useEffect of A screen called.
  2. navigate to B screen from A screen
  3. navigate back to A screen from B. at this time, useEffect is not called.

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的更新状态保持不变(不是从道具加载)

So the updated state of Screen A remain same when comeback to A screen again (Not loading from props)

我不会更改屏幕 B 中的 props.user.但我认为 const [roleID, setRoleID] = useState(props.user.SELECTED_ROLE.id) 至少应该调用这一行.

I am not changing props.user in screen B. But I think const [roleID, setRoleID] = useState(props.user.SELECTED_ROLE.id) this line should be called at least.

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

I am using redux-persist. I think this is not a problem. For navigation, I use this

// 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()
    );
}

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

Is there any callback I can use when the screen appears? What is wrong with my code?

谢谢

推荐答案

当您从 A 导航到 B 时,组件 A 不会被销毁(它保留在导航堆栈中).因此,当您返回时,代码不会再次运行.

When you navigate from A to B, component A is not destroyed (it stays in the navigation stack). Therefore, when you navigate back the code does not run again.

也许是实现您想要使用导航生命周期事件的更好方法(我假设您正在使用 react-navigation),即订阅 didFocus 事件并在组件聚焦时运行任何你想要的代码,例如

Perhaps a better way to acheive what you want to to use the navigation lifecycle events (I am assuming you are using react-navigation) I.e. subscribe to the didFocus event and run whatever code you want whenever the component is focussed E.g

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

不要忘记在适当的时候退订,例如

Don't forget to unsubscribe when appropriate e.g.

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

这篇关于返回屏幕时未在 React Native 中调用 useEffect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆