AsyncStorage
以{"chosenDate":"2018-12-10","text":"llibl"}
格式存储数据。
但我希望它以{'2012-05-22': [{text: 'item 1 - any js object'}]
或'2012-05-25': [{text: 'item 3 - any js object'},{text: 'any js object'}]
格式存储
OR
当我使用componetDidMount()
到getState()
时是否可以更改存储格式?
以下是我的组件的代码:
因此,我有一个带有TextInput和DatePicker的表单以及一个按钮,单击该按钮后,表单条目将使用AsyncStorage
存储。
class Reminder extends Component {
constructor(props) {
super(props);
let formatDate = new Date();
this.state = {
chosenDate: formatDate.toISOString().split('T')[0],
text: '',
};
this.handleChangeInput = this.handleChangeInput.bind(this);
this.saveData = this.saveData.bind(this);
}
handleChangeInput = (input) => {
this.setState({text:input});
}
//save the input
saveData() {
AsyncStorage.setItem("key", JSON.stringify(this.state));
}
render() {
return (
<View>
<Form style={styles.formContainer}>
<View style={styles.formView}>
< TextInput
placeholder = "Set your reminder"
onChangeText={this.handleChangeInput}
value={this.state.text}
/>
<DatePicker
defaultDate={new Date()}
minimumDate={new Date(2018, 1, 1)}
maximumDate={new Date(2019, 12, 31)}
locale={"en"}
timeZoneOffsetInMinutes={undefined}
modalTransparent={false}
animationType={"fade"}
androidMode={"default"}
placeHolderText="Select date"
textStyle={{ color: "green" }}
placeHolderTextStyle={{ color: "#d3d3d3" }}
/>
<Text style={styles.datePicker}>
{this.state.chosenDate}
</Text>
</View>
<View style={styles.footer}>
<Button block success style={styles.saveBtn}
onPress={ () =>
{
this.saveData()
console.log('save data',this.state);
Alert.alert('Yay!!', 'Succefully saved.')
}
}
>
<Icon type='MaterialIcons' name='done' />
</Button>
</View>
</Form>
</View>
);
}
}
export default Reminder;
答案 0 :(得分:1)
// you can achieve this by formatting the state before you store to asyncStorage.
constructor(props) {
super(props);
this.state = {
chosenDate: "2018-12-10",
text: "library1",
text1: "library2"
};
}
async saveData() {
let { chosenDate, ...restOfState } = this.state;
let textArray = Object.entries(restOfState).map(([key, value]) => ({ [key]: value }));
let formattedState = { [chosenDate]: textArray };
await AsyncStorage.setItem("key", JSON.stringify(formattedState));
}
async getData() {
let storedData = await AsyncStorage.getItem("key");
return storedData ? JSON.parse(storedData) : {};
}
render() {
return (
<View>
<Button
title="SaveData"
onPress={() => {
this.saveData().then(resp => {console.log("data saved")});
}}
/>
<Button
style={{ margin: 20, padding: 20 }}
title="getData"
onPress={() => {
this.getData().then(resp => {
console.log("Stored Data", resp);
});
}}
/>
</View>
);
}
// Sample Code
let state = {"chosenDate":"2018-12-10","text":"llibl", text1:"llib2"};
let {chosenDate, ...restOfState} = state;
console.log(`chosenDate: ${chosenDate}, restOfState: ${restOfState}`);
let textArray = Object.entries(restOfState).map(([key, value])=> ({[key]: value}))
let foramttedState = {[chosenDate]:textArray};
console.log('foramttedState :',foramttedState);