启动时从异步存储响应本机加载状态
React Native load state from Async storage on start
状态 "reminders" 使用密钥 "reminders" 保存到 AsyncStorage。
现在,每次应用程序启动时,我都需要使用密钥 "reminders" 从 AsyncStorage 加载 "reminders"。
然后将其显示在 FlatList 中。
我该怎么做?
import React, {useState, Component} from 'react';
import {
StyleSheet,
Text,
View,
SafeAreaView,
FlatList,
} from 'react-native';
import {AsyncStorage} from 'react-native';
function Reminders() {
// REMINDERS
const [reminders, setReminders] = useState([
{day: 'MON', time: new Date(), status: true},
{day: 'TUE', time: new Date(), status: true},
{day: 'WED', time: new Date(), status: true}
]);
return (
<View>
<FlatList
data={reminders}
renderItem={({item, index}) => (
<View><Text>{item}</Text></View>
);
}
export default Reminders;
你可以使用钩子useEffect
:
useEffect(readReminders, []);
function readReminders() {
AsyncStorage.getItem('reminders').then(value=> setReminders(value));
}
状态 "reminders" 使用密钥 "reminders" 保存到 AsyncStorage。 现在,每次应用程序启动时,我都需要使用密钥 "reminders" 从 AsyncStorage 加载 "reminders"。 然后将其显示在 FlatList 中。
我该怎么做?
import React, {useState, Component} from 'react';
import {
StyleSheet,
Text,
View,
SafeAreaView,
FlatList,
} from 'react-native';
import {AsyncStorage} from 'react-native';
function Reminders() {
// REMINDERS
const [reminders, setReminders] = useState([
{day: 'MON', time: new Date(), status: true},
{day: 'TUE', time: new Date(), status: true},
{day: 'WED', time: new Date(), status: true}
]);
return (
<View>
<FlatList
data={reminders}
renderItem={({item, index}) => (
<View><Text>{item}</Text></View>
);
}
export default Reminders;
你可以使用钩子useEffect
:
useEffect(readReminders, []);
function readReminders() {
AsyncStorage.getItem('reminders').then(value=> setReminders(value));
}