我正在使用两个数组present_count和total_count。
present_count [0]将存储第一个主题的计数(单击第一个主题的蓝色按钮的次数),present_count [1]将存储下一个主题的计数,依此类推。
total_count [0]将存储第一个主题的计数(单击第一个主题的蓝色/红色按钮的次数),total_count [1]将存储下一个主题的计数,依此类推。
present_count [i]将出现在斜杠的LHS上,total_count [i]将出现在斜杠的RHS上。
state = {
subjects: [],
text: "",
present_count: [],
total_count: [],
}
present = i => {
this.setState({
present_count: this.state.present_count[i] + 1,
total_count: this.state.total_count[i] + 1
});
AsyncStorage.setItem('PRESENT_COUNT', this.state.present_count[i].toString());
AsyncStorage.setItem('TOTAL_COUNT', this.state.total_count[i].toString());
};
total = i => {
this.setState({
total_count: this.state.total_count[i] + 1,
});
AsyncStorage.setItem('TOTAL_COUNT', this.state.total_count[i].toString());
};
componentDidMount() {
AsyncStorage.getItem('PRESENT_COUNT').then((value) => {
this.setState({ present_count: parseInt(value) });
});
AsyncStorage.getItem('TOTAL_COUNT').then((value) => {
this.setState({ total_count: parseInt(value) });
});
}
render() {
let tick = "\u2713", cross = "\u2573";
return (
<View style={[styles.container, { paddingBottom: this.state.viewPadding }]}>
<FlatList style={styles.list}
data={this.state.subjects}
renderItem={({item, index }) => {
return (
<View>
<View style={styles.listItemCont}>
<Text style={styles.listItem}> { item.text } </Text>
<View style={styles.buttonContainer}>
<Text style={styles.listItem}>
{this.state.present_count[index]} / {this.state.total_count[index]}
</Text>
<View style={styles.button}>
<Button title={tick} onPress={() => this.present(index)} color="blue" />
</View>
<View style={styles.button}>
<Button title={cross} onPress={() => this.total(index)} color="red" />
</View>
</View>
</View>
<View style={styles.hr} />
</View>
)
}}
keyExtractor={ (item, index) => index.toString()}
/>
</View>
);
}
}
问题不是真的关于FlatList
,还有其他问题。其中之一是在反应中修改阵列状态。要修改索引处的值,请执行
let present_count = [...this.state.present_count]; // shallow copy to avoid mutation
present_count[i]++; // increment
this.setState({ present_count }); // update state
+i
AsyncStorage.setItem('PRESENT_COUNT'+i, this.state.present_count[i]);
AsyncStorage.setItem('PRESENT_COUNT', JSON.stringify(this.state.present_count));
AsyncStorage.getItem('PRESENT_COUNT').then((value) => {
this.setState({ present_count: JSON.parse(value) });
});
您必须确定present_count
是数组还是整数。
state = {
present_count: [], // it is an array
...
componentDidMount() {
AsyncStorage.getItem('PRESENT_COUNT').then((value) => {
this.setState({ present_count: parseInt(value) }); // you are parsing it as an integer
});
如果要存储许多整数,请签出multiget以将多个键加载到present_count
中的componentDidmount
数组中。否则,只需使用JSON.parse(value)
获取并解析整个数组。