首页 > 解决方案 > React Native Android:每次获得焦点时重新渲染屏幕

问题描述

我尝试使用建议的方法,例如使用forceUpdate()方法和设置状态,但我意识到所有这些都需要先按下按钮。我也尝试forceUpdate()从构造函数调用该方法,但这警告组件尚未渲染。如何自动重新加载屏幕?

标签: androidreact-native

解决方案


如果您使用反应导航,则可以在重新访问屏幕时使用焦点事件侦听器:

 React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // The screen is focused
      // Call any action
    });

    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

文档


推荐阅读