私はReactJSアプリケーションを構築しています、と私は、このようにデータを保存する必要があります。保存配列 - ReactJS
this.state = {
user: {
name: "",
surname: "",
age: "",
...
instruments: [],
}
}
instruments
状態は性質name
とexperience
で、複数のオブジェクトを含める必要があります。例:私は反応するように新たなんだ
instruments: [
{
name: 'Bass guitar',
experience: 7,
},
{
name: 'Drums',
experience: 1,
}
...
]
は、これまでのところ、私はこれを行うことにより、同様の配列内のデータを保存することができました:
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"} –