我一直在尝试这几天,我的目标是以嵌套数组形式显示状态并使用AsyncStorage同时保存它。我想要显示一个状态并保存它,但是使用嵌套数组它将无法正常工作并且没有错误。
这是我的目标:
“名称”和“价格”应该来自我的api,但为了简单起见,我将使用一些没有api的简单数组。
这是我的代码:
Store.js
const isAndroid = Platform.OS == "android";
const viewPadding = 10;
export default class Store extends Component {
constructor(props) {
super(props);
this.state = {
tasks: [{
id: "Ford" ,
price: "123"
}],
text: "",
}
}
changeTextHandler = (text) => {
this.setState({ text: text });
};
addTask = () => {
let notEmpty = this.state.text.trim().length > 0;
if (notEmpty) {
this.setState(
prevState => {
let { tasks, text, id, price } = prevState;
return {
tasks: tasks.concat({ key: tasks.length, text: text, id: id, price: price }),
id: id,
price: price,
text: "",
};
},
() => Tasks.save(this.state.tasks)
);
}
};
deleteTask = i => {
this.setState(
prevState => {
let tasks = prevState.tasks.slice();
tasks.splice(i, 1);
return { tasks: tasks };
},
() => Tasks.save(this.state.tasks)
);
};
componentDidMount() {
Keyboard.addListener(
isAndroid ? "keyboardDidShow" : "keyboardWillShow",
e => this.setState({ viewPadding: e.endCoordinates.height + viewPadding })
);
Keyboard.addListener(
isAndroid ? "keyboardDidHide" : "keyboardWillHide",
() => this.setState({ viewPadding: viewPadding })
);
Tasks.all(tasks => this.setState({ tasks: tasks || [] }));
}
render() {
return (
<View
style={[styles.container, { paddingBottom: this.state.viewPadding }]}
>
<FlatList
style={styles.list}
data={this.state.tasks}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) =>
<View>
<View style={styles.listItemCont}>
<Text>
{item.id}
{item.price}
{item.text}
</Text>
<Button title="X" onPress={() => this.deleteTask(index)} />
</View>
<View style={styles.hr}/>
</View>
}
/>
<TextInput
style={styles.textInput}
onChangeText={this.changeTextHandler}
onSubmitEditing={this.addTask}
value={this.state.text}
placeholder="Add Tasks"
returnKeyType="done"
returnKeyLabel="done"
/>
</View>
);
}
}
let Tasks = {
convertToArrayOfObject(tasks, callback) {
return callback(
tasks ? tasks.split("||").map((task, i) => ({ key: i, text: task })) : []
);
},
convertToStringWithSeparators(tasks) {
return tasks.map(task => task.text).join("||");
},
all(callback) {
return AsyncStorage.getItem("TASKS", (err, tasks) =>
this.convertToArrayOfObject(tasks, callback)
);
},
save(tasks) {
AsyncStorage.setItem("TASKS", this.convertToStringWithSeparators(tasks));
},
};