在本机中单击抽屉导航器上的选项卡时组件渲染一次

component render one time when click tab on drawerNavigator in react native

我是 React Native 的新手,在调用组件时遇到问题。每当第一次单击抽屉导航器选项卡时,组件渲染和 API 被调用但是当返回主页并再次调用该组件时 API 未被调用。我想回忆那个功能。

这是我的抽屉导航器代码:

const AppDrawerNavigator = createDrawerNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      drawerLabel: 'Home',
      drawerIcon: () => (
        <Icon name="home" size={20} color="#0f1f7b" />
        )
    },
  },
  PreviousInspection: {
    screen: PreviousInspection,
    navigationOptions: {
      drawerLabel: 'Previous Inspection',
      drawerIcon: () => (
        <Icon name="file" size={20} color="#0f1f7b" />
        )
    },
  },
  Logout: {
    screen: Logout,
    navigationOptions: {
        drawerLabel: 'Logout',
        drawerIcon: () => (
          <Icon name="sign-out" size={20} color="#0f1f7b" />
          )
    },
  }
},
{
  drawerBackgroundColor: "#fff",
  contentOptions: {
    activeTintColor: '#000',
    inactiveTintColor: '#000',
    activeBackgroundColor: '#bfc7f3',
    itemStyle: {
      fontSize: 12,
    },
  },
});

react-navigation 有一个 withNavigationFocus HOC,它为你的组件提供一个 isFocused 属性。您可以使用它来确定某个屏幕何时可见。

import { withNavigationFocus } from 'react-navigation';

class YourScreen extends React.Component {

  render() {
     ...
  }

  componentDidUpdate(prevProps) {
    if (this.props.isFocused && !prevProps.isFocused) {
      // Screen has now come into focus, call your method here 
    }
  }

}

export default withNavigationFocus(YourScreen)