I want to Set a Value and Get it in Render with one line code, by adding a Variable between tags. This could shows error:(Can't find variable: storage_key)
import React, { Component } from 'react'
import { View, Text } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
class SyncRu extends Component {
state = {
'storage_Key': ''
}
render() {
const storeData = async (value) => {
try {
await AsyncStorage.setItem('@storage_Key', value)
} catch (e) {
// saving error
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key')
if (value !== null) {
// value previously stored
}
} catch (e) {
// error reading value
}
}
return (
<View>
<Text>
{storage_Key}
</Text>
</View>
)
}
}
export default SyncRu
You have initialized the state incorrectly. Instead of:
state = {
'storage_Key': ''
}
You have to use:
this.state = {storage_Key: ""};
After you access your data from AsyncStorage you have to use setState, for updating your UI.
const value = await AsyncStorage.getItem('@storage_Key')
if (value !== null) {
this.setState({
storage_Key: value
});
}
Also have a look at the documentation of React State. React State Documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.