1

我添加了一个新的联系对象并尝试在 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>}
          />
4

3 回答 3

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.

于 2019-06-14T14:49:34.053 回答
1

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

refreshContactsList = () => {
    const newContact = {data: [{name:this.state.contactName, phone:this.state.contactPhone}]};
    this.setState({ contacts: [...this.state.contacts, newContact]})
  }
于 2019-06-14T16:46:20.927 回答
0

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

this.setState(state => {
    return {contacts: [...state.contacts, newContact]};
});
于 2019-06-14T13:31:58.167 回答