保存状态中的对象数组 - ReactJS

时间:2016-12-10 10:44:26

标签: arrays object reactjs state

我正在构建一个ReactJS应用程序,我需要以这种方式存储数据:

this.state = {
    user: {
        name: "",
        surname: "",
        age: "",
        ...
        instruments: [],
    }
}

instruments州需要包含多个对象,其中包含属性nameexperience。一个例子:

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>

有关如何解决此问题的任何想法?感谢

2 个答案:

答案 0 :(得分:4)

Instrument是一个对象,你试图渲染它,使用你想渲染的特定值,试试这个:

musicListenChange(val){
    let user = this.state.user;  
    user['music_listen'] = val.value;
    this.setState({user: user);
}

saveInstrument(){
    let user = this.state.user;
    user['instruments'] = user['instruments'] ? user['instruments'] : [];
    user['instruments'].push(this.state.instruments);
    this.setState({user: user});
}

在渲染功能中使用此:

{this.state.user.instruments ? 
     this.state.user.instruments.map((instrument, index) => {
        return (<button className="btn btn-default">{instrument.name}</button>)
     })
:<div/>
}

答案 1 :(得分:1)

问题在于:

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

当意识到instrument是一个JavaScript对象(你说你的instruments数组包含结构为{name: "string", experience:"string"}的对象)时,错误信息变得清晰:你试图插入一个对象作为<button>元素的子元素,这是不允许的,因为React不知道如何显示对象。如果您使用instrument.nameinstrument.experience代替(字符串),您的代码就可以使用。