react-native - 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);
解决方案
在反应导航 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>
)
}
干杯!
推荐阅读
- python - Python 等价于 unzip -p
- c# - 从 Gen2 datalake 获取数据时出错 - 确保 Authorization 标头的值正确形成,包括签名
- c++ - 为什么从上方直接俯视形状时不会呈现形状?
- javascript - 从 RNPushNotification 获取第一次执行的 Token
- python - PyInstaller 无法创建 base_library.zip
- javascript - SyntaxError: Unexpected token < in JSON at position 0 in Google Sheets Apps Script Tutorial
- javascript - 如何使用在样式标签中包含 css 的 javascript 将 html 文件转换为 pdf
- netlogo - Netlogo 的 SEIR 模型中的 n-of 错误
- ruby-on-rails - 在 Rails 中,我使用的是 DateTime.current.in_time_zone(user's timezone")。我真的需要在最后添加 utc 吗?
- r - 通过组合列表输出创建数据框