react-native - 将对象添加到数组并刷新 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>}
/>
解决方案
您没有正确使用链接的解决方案。缺少环绕括号。
this.setState(state => ({
contacts: [...state.contacts, newContact]
}));
我认为你可以缩短
this.setState({ contacts: [...this.state.contacts, newContact] });
我想补充一点
this.refreshContactsList = this.refreshContactsList.bind(this);
没有必要,因为refreshContactList
它是一个箭头函数,你不会this
在里面丢失指针。如果您将其声明为refreshContactList() {...}
需要绑定this
.
推荐阅读
- java - 对于两个整数用户输入,如何检测在第一个输入上传递了一个字符串?
- java - 将列表值获取到二维数组并检索
- java - 为什么程序在我的 showPanel 方法中的 setVisible 处抛出错误“找不到符号”?
- php - 传递连接字符串时,我无法在 PHP 中删除目录?
- android - 如何获取Android内部下载目录的路径?
- swift - 如何将自定义类的子类添加到 GameScene?
- android-studio - 如何使用 Chromebook 上的 Android Studio 将应用程序部署到 Android 手机?
- javascript - 从结帐中删除国家/地区,但不从购物车中删除
- c++ - 使用系统 C++ 杀死进程
- django - create() 接受 1 个位置参数,但给出了 2 个