将对象添加到数组JS [英] Add Object to Array JS

查看:1923
本文介绍了将对象添加到数组JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cannot add new object to array. Why?

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

我得到的错误:未定义不是对象(正在评估'this.state.messagesArray.push')

The error, which i got: undefined is not object (evaluating 'this.state.messagesArray.push')

推荐答案

如@Sam Onela在上面的注释中所建议,您在状态对象中没有messagesArray键,或者messagesArray不是状态对象的属性,也 > 尝试避免使用push ,这是一种变异函数,请尝试使用 concat spread 运算符.您可以尝试以下解决方案克服这个问题

As suggested by @Sam Onela in comment above, you don't have messagesArray key within state object or messagesArray is not a property of state object, also try to avoid to use push, that is a mutating function instead try concat and spread operator.You can try following solutions to overcome the issue

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

这篇关于将对象添加到数组JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆