首页 > 解决方案 > 一旦我设置了 screenProps 的 setState,如何避免在 tabNavigator 中重新渲染屏幕?

问题描述

我正在一个 react native 项目中实现推送通知,我需要从应用程序的父组件通过 reactNavigation screenProps 为 BottomTabNavigator 传递参数。一旦我收到通知,并且我更改状态以更新将指示必须更新的子组件的参数,就会对应用程序进行完整的重新渲染。这是我的代码:

class AppLayout extends Component {
  state = {
    updatePushNotifications: false
  }

  handleActivatePushNotifications = () => {
    this.handlePushNotificationMessageListener();
  }

  handlePushNotificationMessageListener = async () => {
   this.notificationListener = firebase.notifications().onNotification((notification) => {
     const { title, body } = notification;
     console.log(notification);
     console.log('notificationListener');

     //SETSTATE FOR UPDATE CALLS IN CHILD COMPONENTS
     this.setState({
       updatePushNotifications: true
     });

     this.showAlert(title, body);
   });
  }

  showAlert = (title, message) => {
     Alert.alert(
      title,
      message,
      [
       {text: 'OK', onPress: () => console.log('OK Pressed')},
      ],
      {cancelable: false},
     );
  }

  // The entire navigation component is re-rendered once the setState is executed
  render () {
    return (
      <Layout
        screenProps={{
          updatePushNotifications: this.state.updatePushNotifications
        }}
      />
    );
  }
}

当我更新通过 screenProps 传递的任何参数时,如何防止重新渲染应用程序?

提前感谢您的帮助

标签: javascriptreact-nativereact-navigationreact-native-firebase

解决方案


如果您在渲染方法中使用状态,它总是会随着状态更改重新渲染您的应用程序。您可以在类中定义一个变量并对其进行更新。然后将其传递给道具。但要小心,因为如果你不进行 forceUpdate,你就看不到更改。


推荐阅读