【发布时间】:2017-04-25 18:29:40
【问题描述】:
我正在构建一个 ReactJS 应用程序,我需要以这种方式存储数据:
this.state = {
user: {
name: "",
surname: "",
age: "",
...
instruments: [],
}
}
instruments 状态需要包含多个对象,属性为name 和experience。一个例子:
instruments: [
{
name: 'Bass guitar',
experience: 7,
},
{
name: 'Drums',
experience: 1,
}
...
]
我是 React 新手,到目前为止,我已经能够通过这样做将数据保存在类似的数组中:
musicListenChange(val){
let musicListenArray = this.state.user.music_listen ? this.state.user.music_listen : [];
musicListenArray.push(val.value);
this.setState({user: {...this.state.user, music_listen: musicListenArray}});
}
但是,当我尝试使用以下代码保存对象时,我收到一个错误:
saveInstrument(){
// save current instruments state in array, or create an empty one
let array = this.state.user.instruments ? this.state.user.instruments : [];
// in this.state.instruments I saved a temporary copy of the selected instrument, put it in the array
array.push(this.state.instruments);
this.setState({user: {...this.state.user, instruments: array }});
console.log('instrum. state: ', this.state.user.instruments);
}
错误代码
Uncaught Error: Objects are not valid as a React child (found: object with keys {name, experience}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `EditProfile`.
我的 EditProfile 乐器渲染部分
<div className="container-tags">
{this.state.user.instruments ? this.state.user.instruments.map(function (instrument, index) {
return <button className="btn btn-default">{instrument}</button>;
}) : <div></div>}
</div>
关于如何解决这个问题的任何想法?谢谢
【问题讨论】:
-
this.state.instruments里面有什么? -
在 this.state.instruments 我保存 {name: "string", experience:"string"}
标签: arrays object reactjs state