react-native - 平面列表未在状态更改时更新
问题描述
我正在创建晚餐决策者应用程序,并希望将项目从用户输入添加到数组中。输入添加到数组列表并显示在警告框中,但不会重新加载 FlatList。请帮助这是我的代码。
constructor(props){
super(props);
this.state = {items:[{key:'Pasta'},{key:'Pizza'}],userdata:''}
}
render() {
return (
<Container>
<Header></Header>
<Content style={{padding:20}}>
<Text style={{fontSize: 30, textAlign:'center', marginVertical:30,}}>Food Decider</Text>
<Item floatingLabel>
<Label>Add Item</Label>
<Input
onChangeText={(text) => this.setState({userdata:text})}
/>
</Item>
<Button block success style={{marginTop: 20,}}
onPress={this.onSubmit.bind(this)}
>
<Text>Add Item</Text>
</Button>
<FlatList
data = {this.state.items}
renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
/>
</Content>
</Container>
);
}
onSubmit(){
this.state.items.push({key:this.state.userdata});
alert(JSON.stringify(this.state.items));
}
谢谢。
解决方案
您需要在 FlatList 中使用 prop legacyImplementation=true 以便它对 FlatList 进行实时更改。
利用:
<FlatList legacyImplementation=true />
推荐阅读
- bulma - Bulma Extensions switch:我如何让它切换
- python - 从列表中的元组访问第n个元素,但元组的长度不同
- linux - 如何通过命令行在 linux 中打开唯一的每个用户的 firefox 实例?
- c - 如何将 double 舍入为 0.00005?
- javascript - 如何从特定索引遍历对象数组
- linux - 执行 git push 时出现大文件的问题
- terraform - 提供者不是 terraform 中的预期
- linux - 如何在不保留原始文件的情况下将日志文件一分为二?
- c# - 如何使用 microsoft graph api 在日历中创建事件?
- mysql - 以最近的时间戳连接表