React Native AsyncStorage获取布尔值用于PDF缓存参数问题求助
解决AsyncStorage返回Promise无法直接传给PDF组件cache参数的问题
嘿,我完全懂你现在卡在哪了——async函数天然返回Promise,所以你直接把this.getCache()赋值给bool,拿到的根本不是布尔值,而是一个待处理的Promise对象。咱们一步步把这个问题理顺:
第一步:修正getCache函数,让它正确返回布尔值
你当前的getCache里,await AsyncStorage.getItem之后的回调完全没必要,直接解析返回值就行,还要考虑初始值为null的情况:
async getCache () { const value = await AsyncStorage.getItem('cache'); // 若本地没存过值,默认设为false const cacheState = value ? JSON.parse(value) : false; console.log(cacheState); return cacheState; }
第二步:在组件挂载时加载缓存状态到state
利用React的componentDidMount生命周期,在组件刚加载完成时,把本地缓存的状态读取出来存到组件state里:
componentDidMount() { this.loadInitialCache(); } async loadInitialCache() { const cacheState = await this.getCache(); this.setState({ cache: cacheState }); }
第三步:修正缓存状态切换的逻辑
你当前的点击事件和saveCache逻辑有点绕,应该先更新state,再把新状态同步到本地存储:
// 重构saveCache,接收新的缓存状态作为参数 saveCache(newCacheState) { AsyncStorage.setItem('cache', JSON.stringify(newCacheState)); console.log(`已存储缓存状态:${newCacheState}`); } // 修改切换按钮的 onPress 逻辑 <TopNavigationAction icon={pin} onPress={() => { const newCacheState = !this.state.cache; // 先更新state,状态更新完成后再同步到本地 this.setState({ cache: newCacheState }, () => { this.saveCache(newCacheState); }); }} status='Partager' > {/* 按钮文字根据状态动态变化,更直观 */} {this.state.cache ? '关闭缓存' : '开启缓存'} </TopNavigationAction>
第四步:用state里的布尔值传给PDF组件
现在直接把state中的cache值传给PDF的cache参数就可以了,因为state里已经是咱们需要的布尔值:
<Pdf source={{ uri: `http://10.1.0.248/${file.path}/${file.filename}`, cache: this.state.cache}} style={styles.pdf} enablePaging={true} onLoadComplete={(numberOfPages, filePath) => { // 注意:不要直接修改state数组,用函数式更新保证状态正确性 this.setState(prevState => ({ filePath: [...prevState.filePath, filePath], numberOfPages: numberOfPages })); }} onPageChanged={(page, numberOfPages) => { this.setState({ page: page }); }} />
额外小提醒
- 不要直接修改state里的数组(比如
this.state.filePath.push(filePath)),React的state是不可变的,必须通过setState来更新。 - 你初始state里的
navigation和route完全没必要存,直接用this.props.navigation和this.props.route就好,props会自动同步最新值。
这样修改后,组件一加载就会从本地读取缓存状态,点击切换按钮时会同时更新state和本地存储,PDF组件也能拿到正确的布尔值作为cache参数啦。
内容的提问来源于stack exchange,提问作者Dirk
相关产品推荐
相关产品推荐

