如果它在iOS 上,你可能忘记了pod install。
把这个粘贴到ios/Podfile:
pod 'RNCAsyncStorage', :path => '../node_modules/@react-native-community/async-storage'
那么就做cd ios && pod install
编辑。
我从头开始创建了一个项目,这是我为使 asyncStorage 在 iOS 和 Android 上运行所做的步骤:
1) react-native init AsyncTest
2)npm i @react-native-community/async-storage
(在此步骤中尝试使用 asyncStorage 会显示错误,但适用于 Android)
3) 将这个 pod 粘贴到 Podfile 中:
pod 'RNCAsyncStorage', :path => '../node_modules/@react-native-community/async-storage'
4) 从终端,假设您在项目文件夹中,请执行 cd ios 和 pod install
5) 项目在 iOS 上成功运行并正常运行。
react-native 版本是 0.60.4
这就是项目测试 App.js 用于测试的方式:
import React from 'react';
import { View } from 'react-native';
import AsyncStorageTest from './AsyncStorageTest'
const App = () => {
return (
<View>
<AsyncStorageTest />
</View>
);
};
export default App
而 AsyncStorageTest 是:
import React, { Component } from 'react'
import { View, Text, Button } from 'react-native'
import AsyncStorage from '@react-native-community/async-storage';
export class AsyncStorageTest extends Component {
constructor(props) {
super(props)
this.state = {
storedData: "myValue"
}
}
storeData = async () => {
console.log("inside storeData")
try {
await AsyncStorage.setItem('Test', 'TestValue')
} catch (e) {
console.log(e)
}
}
getData = async () => {
console.log("inside getData")
try {
const value = await AsyncStorage.getItem('Test')
this.setState({ storedData: value })
} catch (e) {
// error reading value
}
}
render() {
return (
<View style={{ marginTop: 40 }}>
<Text> {this.state.storedData}</Text>
<Button title={"storeData"} onPress={this.storeData}></Button>
<Button title={"getData"} onPress={this.getData}></Button>
</View>
)
}
}
export default AsyncStorageTest
经过测试和工作,看看你是否遗漏了什么。
确保 @react-native-community/async-storage 与您的项目取消链接。