首页 > 解决方案 > 将对象添加到数组并刷新 sectionList

问题描述

我添加了一个新的联系对象并尝试在 SectionList 中显示它。但是当我试图将一个对象放入数组时,我收到一个错误:TypeError: undefined is not an object (evalating 'n.data.length')

我使用此链接中的说明来解决问题。 如何在反应状态下将新对象作为值添加到数组中

constructor(props) {
    super(props);   

    this.state = {
      contacts : [],
      newContactDialogVisible: false,
      contactName : '',
      contactPhone : ''
    }
  }
refreshContactsList = () => {
    const newContact = {'name': this.state.contactName, 'phone': this.state.contactPhone};
    Alert.alert(newContact.name + " " + newContact.phone); // Alert working and shows the right data
    this.setState({ contacts: [...this.state.contacts, newContact] });
  }
<SectionList
            sections={this.state.contacts}
            renderItem={({item, index, section}) => <Text key={index}>{item}</Text>}
          />

标签: react-nativereact-native-sectionlist

解决方案


您没有正确使用链接的解决方案。缺少环绕括号。

this.setState(state => ({
  contacts: [...state.contacts, newContact]
}));

我认为你可以缩短

this.setState({ contacts: [...this.state.contacts, newContact] });

我想补充一点

this.refreshContactsList = this.refreshContactsList.bind(this);

没有必要,因为refreshContactList它是一个箭头函数,你不会this在里面丢失指针。如果您将其声明为refreshContactList() {...}需要绑定this.


推荐阅读