我有一个相对简单的应用程序(我的第一个),需要显示从 GraphQL 查询检索然后存储在 AsyncStorage 中的信息。在您关闭数据/Wifi 连接并重新启动应用程序之前,一切正常 - 它不会加载与网络打开时相同的本地数据。这在物理或模拟的Android设备上是相同的。
除非用户最初设置其详细信息,否则不会进行数据调用。该应用程序是使用 Expo 和 AWS Amplify 的 2.7.1 版构建的。我在最后一个问题上浪费了几天时间,并在Expo SecureStore和Amplify Cache上获得了相同的行为,并且我不愿意沿着学习路线前进,并在如此简单的应用程序上包含Redux...
//import from react native not react
import { AsyncStorage } from 'react-native'
//calling a function as app loads
componentDidMount() {
this._loadInitialState();
}
//retrieving String from AsyncStorage
_loadInitialState = async () => {
try {
const policyNum = await AsyncStorage.getItem('policyNum')
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.state.policyNumSet = true
try {
await AsyncStorage.setItem('policyNum', policyNumber)
} catch (err) {
//...
}
}
}
错了改变状态的事实。
在哪里执行此操作:
this.state.policyNumSet = true
你应该像这样使用 setState() 函数更改状态:
this.setState({ policyNumSet: true })
与外部API的冲突
你在存储字符串吗? 异步存储只能存储字符串。尝试使用 JSON.stringify 和 JSON.parse
_loadInitialState = async () => {
try {
var policyNum = await AsyncStorage.getItem('policyNum')
policyNum = JSON.parse(policyNum) // converting to original
//...
} catch {
//...
}
//setting state
if (policyNum != null && policyNum != undefined) {
this.setState({ policyNum: policyNum })
//...
}
//the original setting of the item
setPolicyDetails = async () => {
if (this.state.policyNum != null) {
const policyNumber = this.state.policyNum
this.setState({ policyNumSet: true })
try {
var policyNumberString = JSON.stringify(policyNumber)
await AsyncStorage.setItem('policyNum', policyNumberString) //converting to string
} catch (err) {
//...
}
}
}