addListeners有时不起作用-反应本机选项卡导航

时间:2020-05-16 15:56:43

标签: react-native react-navigation react-navigation-bottom-tab

我使用了反应导航的标签导航。每次按下选项卡时,我需要在componentDidMount中调用loadData函数。所以我在其中使用addListener。但是问题在于显示数据花费的时间太长。有时它可以无缝运行,有时只显示“ Loading Data ...”。 我是否正确使用addListener?预先感谢。

Home.js

state = {
  storageCheck: true
};

componentDidMount() {
    this._unsubscribe = this.props.navigation.addListener('willFocus', () => {
      this.loadData();
    });
}

componentWillUnmount() {
    this._unsubscribe.remove();
}

loadData = () => {
    this.setState({
        storageCheck: false
    })
}

render() {
if (this.state.storageCheck) {
  return <View>
    <Text>Loading Data...</Text>
  </View>
}
return (
    <View>
        <Text>Data</Text>
    </View>
)}

标签导航

const TabNavigator = createBottomTabNavigator({
  Home: {
    screen: Home
  },
  Profile: {
    screen: Profile,
    navigationOptions: ({ navigation }) => ({
      // title: 'Profile',
    })
  },
  Setting: {
    screen: Setting,
  }
},
  {
    defaultNavigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, tintColor }) => {
        const { routeName } = navigation.state;
        let iconName;
        if (routeName === 'Home') {
          iconName = 'home';
        } else if (routeName === 'Profile') {
          iconName = 'account-circle';
        } else if (routeName === 'Setting') {
          iconName = 'settings';
        }

        return <MaterialIcons name={iconName} size={28} color={tintColor} />;
      },
    })
  }
);

export default createAppContainer(TabNavigator);

2 个答案:

答案 0 :(得分:1)

在反应导航v4中。

您可以使用 await-async 功能。

state = {
  storageCheck: true,
  loader: true,
  someData: null
};

componentDidMount() {
    this._unsubscribe = this.props.navigation.addListener('willFocus', () => {
      this.loadData();
    });
}

componentWillUnmount() {
    this._unsubscribe.remove();
}

loadData = async() => {
    this.setState({
        someData: await AsyncStorage.getItem("SOME_KEY"),
        storageCheck: false,
        loader: false
    })
}

render() {
  return (
      <View>
       {this.state.someData ? (
        <Text>data is loaded</Text>
       ) : (
        <Text> loading ... </Text>
       )}
      </View>
  )
}

欢呼!

答案 1 :(得分:0)

这是一个明确的解决方案。我认为您可以使用挂钩功能组件。 我使用与此相关的解决方案

write

欢呼!