首页 > 解决方案 > addListeners 有时不起作用 - 反应本机选项卡导航

问题描述

我使用了 react-navigation 的标签导航。每次按下选项卡时,我都需要在 componentDidMount 中调用 loadData 函数。所以我在其中使用了 addListener 。但问题是显示数据花费的时间太长。有时它可以无缝运行,有时它一直只显示“正在加载数据......”。我是否正确使用了 addListener?提前致谢。

主页.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);

标签: react-nativereact-navigationreact-navigation-bottom-tab

解决方案


在反应导航 v4.

您可以使用等待异步功能。

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>
  )
}

干杯!


推荐阅读