将对象添加到数组并刷新sectionList

时间:2019-06-14 13:15:22

标签: react-native react-native-sectionlist

我添加了一个新的联系人对象,并试图在SectionList中显示它。但是,当我尝试将对象放入数组时,出现错误:TypeError:undefined不是对象(正在评估“ n.data.length”)

我使用了此链接中的说明来解决问题。 how to add a new object as a value to an array in the react state

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>}
          />

3 个答案:

答案 0 :(得分:1)

您没有正确使用链接的解决方案。缺少包装支架。

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

我认为您可以选择更短的

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

我想补充一下

this.refreshContactsList = this.refreshContactsList.bind(this);
不需要

,因为refreshContactList是箭头函数,并且不会丢失this指针。如果您将其声明为refreshContactList() {...},则需要绑定this

答案 1 :(得分:1)

最后,我找到了正确的语法:

refreshContactsList = () => {
    const newContact = {data: [{name:this.state.contactName, phone:this.state.contactPhone}]};
    this.setState({ contacts: [...this.state.contacts, newContact]})
  }

答案 2 :(得分:0)

我认为问题出在错误的箭头函数语法上。试试这个

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