虽然现在看来是很简单的一个组件,可自己用了两个星期都没有解决;记录哈自己的坑;
react-native-clear-app-cache 这个组件是上海的一个前端大哥封转的
import { View, Text, StyleSheet,NativeModules, Dimensions, BackHandler, Platform, Image, Alert, ScrollView, InteractionManager, Linking } from 'react-native'
import clear from 'react-native-clear-app-cache'
/**
* 设置
*/
export default class Setting extends Component {
constructor(props) {
super(props)
this.state = {
unit : '', // 缓存单位
cacheSize : "0", // 缓存
}
clear.getAppCacheSize((value,unit)=>{ // 这个一定要写在构造函数里面
this.setState({ // 要是不写在里面,会报getAppCacheSize是Undefined
cacheSize:parseInt(value), //缓存大小
unit:unit //缓存单位
})
});
}
render() {
return (
<ScrollView>
<View style={styles.container}>
<TopHeader title={'设置'} leftBtn={leftBtn.BACK} backPath={'Info'} navigation={this.props.navigation}/>
<View>
<ListItem
title={'清除缓存'}
containerStyle={{borderBottomWidth : 0, height: scaleSize(100)}}
titleStyle={{fontSize: 14}}
titleContainerStyle={styles.titleContainer}
hideChevron={true}
onPress={()=>{this.refs['clearCache'].show()}}
rightTitle={this.state.cacheSize+this.state.unit}
/>
</List>
</View>
</View>
<AlertDialog
messageText={'确定要清除缓存吗?'}
negativeText={'取消'}
positiveText={'确定'}
onPress={(data) => data ? this.clearCache() : null}
ref={'clearCache'}
>
</AlertDialog>
</ScrollView>
);
}
clearCache(){ // 清除缓存
clear.clearAppCache(() => {
console.log("清除成功");
clear.getAppCacheSize((value, unit) => {
this.setState({
cacheSize: value, // 缓存大小
unit: unit // 缓存单位
})
});
});
}
componentWillUnmount() {
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress',()=>{});
}
}
}
const styles = StyleSheet.create({
container: {
backgroundColor : '#FAFAFA',
height: SCREEN_HEIGHT,
},
lists : {
marginBottom: 20,
backgroundColor : '#FFFFFF',
borderTopWidth : 0,
marginTop: 0,
},
titleContainer : {
marginLeft : -10,
marginTop : 5
},
logoutBtn : {
width : SCREEN_WIDTH * 0.92,
height : SCREEN_HEIGHT * 0.08,
borderRadius : 5,
marginTop : 40,
alignItems:'center',
justifyContent: 'center',
}
});