将对象添加到数组 JS



我无法将新对象添加到数组中。为什么?

  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"(

正如

@Sam Onela在上面的评论中所建议的那样,状态对象中没有messagesArray键或messagesArray不是状态对象的属性,也尽量避免使用push,这是一个变异函数,而是尝试concatspread运算符。您可以尝试以下解决方案来解决此问题

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
});

你有一个简单的错别字。您已将数组设置为 state.messagesSource,并尝试添加到不存在的 state.messagesArray。有一个消息数组变量,但在状态上没有可用的变量。

相关内容

  • 没有找到相关文章

最新更新