我无法将新对象添加到数组中。为什么呢?
var messagesArray = [
{message: "Hello", style: styles.nikkiMes},
{message: "Okkkk", style: styles.userMes}
];
this.state = {
messagesSource: ds.cloneWithRows(messagesArray.slice()),
inputMes: ''
};
添加:
this.state.messagesArray.push({
message: this.inputMes,
style: styles.userMes
});
this.setState({
messagesSource: ds.cloneWithRows(this.state.messagesArray.slice())
});
错误,我得到:undefined不是对象(评估' this.state.messagesArray.push')
答案 0 :(得分:0)
你有一个简单的拼写错误。您已将数组设置为state.messagesSource,并且正在尝试添加到state.messagesArray,该状态不存在。有一个messagesArray变量,但状态不可用。
答案 1 :(得分:0)
正如@Sam Onela在上面的评论中所建议的,你在状态对象中没有messagesArray键,或者messagesArray不是state对象的属性, 也试图避免使用push ,这是一个变异函数,而不是尝试 concat 和传播运算符。您可以尝试以下解决方案来克服此问题
1)
var messagesArray = [
{message: "Hello", style: styles.nikkiMes},
{message: "Okkkk", style: styles.userMes}
];
this.state = {
messagesSource: ds.cloneWithRows(messagesArray.slice()),
inputMes: ''
};
//these lines of code will not be needed if you are using spread operator
messagesArray.concat({ //replaced push with concat, meassageArray is a global object
message: this.inputMes,
style: styles.userMes
});
this.setState({
messagesSource: ds.cloneWithRows(messagesArray.slice())
//messagesSource: ds.cloneWithRows([...messageArray, {message: this.inputMes,style: styles.userMes}]) // see how you can directly use spread operator
});
2)
var messagesArray = [
{message: "Hello", style: styles.nikkiMes},
{message: "Okkkk", style: styles.userMes}
];
this.state = {
messagesSource: ds.cloneWithRows(messagesArray.slice()),
inputMes: '',
messagesArray :messagesArray //I included messagesArray within state
};
this.setState((prevState, props)=>{
messageArray:[...prevState.messageArray, {message: this.inputMes,style: styles.userMes}]
})
this.setState({
messagesSource: ds.cloneWithRows(this.state.messagesArray) //first solution will be most fit for your case as messageArray would not have been updated till now
});