我想要的是,在按下“保存”图标之后,通过将新创建的对象添加到数组中,然后将该数组保存在Asyn Storage中,以更新“数据”状态(保留当前的Asyn Storage元素)。我知道更改状态是一个异步操作,尽管我很难弄清楚如何解决它。到目前为止,状态尚未更新,我将空数组保存在Asyn存储中(因为现在我没有设法在其中保存任何数据)。我的代码:
import React, {useState, useEffect} from "react";
import {StyleSheet, Text, View, Image, AsyncStorage, ScrollView, FlatList, ImageBackground} from "react-native";
import Constants from "expo-constants";
import {colors} from "../../theme";
import MainText from "../Versatile_components/MainText";
import SubText from "../Versatile_components/SubText";
import TextInputGKC from "../Versatile_components/TextInputGKC";
import Icon from 'react-native-vector-icons/FontAwesome';
import {themes} from "react-native/RNTester/js/components/RNTesterTheme";
import AdditionalText from "../Versatile_components/AdditionalText";
import ButtonGKCText from "../Versatile_components/Button-GKC-Text";
const newPlan = ({route, navigation}) => {
const countryName = route.params.pickedCountry.name;
const currency = route.params.pickedCountry.currencies.map(el => `${el.symbol}`);
const tripHeader = `Trip to ${countryName}`;
let budgetLabel = `Budget (${currency}):`;
const [data, setData] = useState([]);
const storageUT = "UpcomingTrips";
const load = async () => {
try {
let data = await AsyncStorage.getItem("UpcomingTrips");
let tripData = JSON.parse(data);
if (tripData !== null) {
setData(tripData);
}
} catch (error) {
alert(error);
}
};
useEffect(() => {
load();
}, [data]);
//form inputs - state values
const [title, setTitle] = useState("");
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [budget, setBudget] = useState("");
const [luggageItem, setLuggageItem] = useState("");
const [visitItem, setVisitItem] = useState("");
const [luggageContent, setLuggageContent] = useState([]);
const [visitList, setVisitList] = useState([]);
const [screen, setScreen] = useState(false);
const addLuggageItem = () => {
if (luggageItem.length > 0) {
setLuggageContent(prevState => [...prevState, luggageItem]);
setLuggageItem("");
}
};
const addVisitItem = () => {
if (visitItem.length > 0) {
setVisitList(prevState => [...prevState, visitItem]);
setVisitItem("");
}
};
const addTrip = () => {
const tripObject = {
title: `${countryName}, ${title}`,
startDate,
endDate,
budget,
luggageContent,
visitList
};
setData(prevState => [...prevState, tripObject]);
};
/* const toHome =()=>{
navigation.navigate("Explore")
};*/
const save = async ()=>{
addTrip();
try {
await AsyncStorage.setItem(storageUT, JSON.stringify(data));
console.log("plan saved",data);
} catch (error) {
console.log(error)
}
setScreen(true);
};
let content = `Your plan was successfully saved!`;
let backgroundImg = require('../../assets/ivan-bandura-rXNWenGhDm0-unsplash.jpg');
if (screen === false) {
return (
<View style={styles.AndroidSafeAreaViewContainer}>
<View style={{alignItems: "flex-end"}}>
<Icon name="save" color={colors.secondary} size={30} onPress={save}/>
</View>
<MainText color="#fff" content={tripHeader} style={{marginTop: 50}}/>
<View style={[styles.inputContainer, {paddingBottom: 15}]}>
<SubText color="#fff" content="Trip title:"/>
<TextInputGKC width="65%" selectionColor="pink" marginTop={15} inputValue={title}
inputChange={(value) => setTitle(value)}/>
</View>
<SubText color="#fff" content="Dates"/>
<View style={styles.inputContainer}>
<SubText color="#fff" content="Starting date:"/>
<TextInputGKC placeholderTextColor="grey" placeholder="yyyy-mm-dd" keyboardType="numeric"
width="65%"
selectionColor="pink" marginTop={10} inputValue={startDate}
inputChange={(value) => setStartDate(value)}/>
</View>
<View style={[styles.inputContainer, {paddingBottom: 15}]}>
<SubText color="#fff" content="Ending date:"/>
<TextInputGKC placeholderTextColor="grey" placeholder="yyyy-mm-dd" keyboardType="numeric"
width="65%"
selectionColor="pink" marginTop={10} inputValue={endDate}
inputChange={(value) => setEndDate(value)}/>
</View>
<View style={[styles.inputContainer, {paddingBottom: 15}]}>
<SubText color="#fff" content={budgetLabel}/>
<TextInputGKC keyboardType="numeric" width="65%" selectionColor="pink" marginTop={10}
inputValue={budget} inputChange={(value) => setBudget(value)}/>
</View>
{/*Things to take*/}
<View style={[styles.inputContainer, {justifyContent: "flex-start"}]}>
<Icon name="suitcase" color={colors.secondary} size={25} style={{marginRight: 15}}/>
<SubText color="#fff" content="My luggage:"/>
</View>
<View style={[styles.inputContainer, {paddingBottom: 15}]}>
<TextInputGKC selectionColor="pink" marginTop={10} flexGrow={1} marginRight={10}
inputValue={luggageItem}
inputChange={(value) => setLuggageItem(value)}/>
<Icon name="plus-square" color={colors.secondary} size={25} style={{marginRight: 15}}
onPress={addLuggageItem}/>
</View>
<FlatList data={luggageContent} keyExtractor={(item) => item} renderItem={({item}) => (
<View style={styles.listItems}>
<SubText color="#fff" content={item}/>
<Icon name="trash" color={colors.secondary} size={20} />
<Icon name="edit" color={colors.secondary} size={20} />
</View>
)}/>
{/*Places to visit*/}
<View style={[styles.inputContainer, {justifyContent: "flex-start", paddingTop: 15}]}>
<Icon name="compass" color={colors.secondary} size={25} style={{marginRight: 15}}/>
<SubText color="#fff" content="Places to visit:"/>
</View>
<View style={[styles.inputContainer, {paddingBottom: 15}]}>
<SubText color="#fff" content="City/Site:"/>
<TextInputGKC width="65%" selectionColor="pink" marginTop={15} inputValue={visitItem}
inputChange={(value) => setVisitItem(value)}/>
<Icon name="plus-square" color={colors.secondary} size={25} style={{marginRight: 15}}
onPress={addVisitItem}/>
</View>
<FlatList data={visitList} keyExtractor={(item) => item} renderItem={({item}) => (
<View style={styles.listItems}>
<SubText color="#fff" content={item}/>
<Icon name="trash" color={colors.secondary} size={20} />
<Icon name="edit" color={colors.secondary} size={20} />
</View>
)}/>
</View>
)
} else {
return (
<View style={styles.AndroidSafeAreaViewContainerImage}>
<ImageBackground source={backgroundImg} style={styles.wallPaper}>
<MainText color="#fff" content={content}/>
</ImageBackground>
</View>
)
}
}
;
export default newPlan;
const styles = StyleSheet.create({
AndroidSafeAreaViewContainer: {
flex: 1,
backgroundColor: colors.primary,
paddingTop: Constants.statusBarHeight,
paddingHorizontal: 15,
},
AndroidSafeAreaViewContainerImage: {
flex: 1,
backgroundColor: colors.primary
},
inputContainer: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
flexWrap: "wrap"
},
listItems: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
flexWrap: "wrap"
},
wallPaper: {
flex: 1,
width: "100%",
resizeMode: "cover",
justifyContent: "center",
alignItems: "center"
}
});