Я строю приложение ReactJS, и мне нужно хранить данные таким образом:Сохранить массив объектов в состоянии - 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"} –