首页 > 解决方案 > 平面列表未在状态更改时更新

问题描述

我正在创建晚餐决策者应用程序,并希望将项目从用户输入添加到数组中。输入添加到数组列表并显示在警告框中,但不会重新加载 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));
  }

谢谢。

标签: react-native

解决方案


您需要在 FlatList 中使用 prop legacyImplementation=true 以便它对 FlatList 进行实时更改。

利用:

<FlatList legacyImplementation=true />

推荐阅读