为什么我得到[对象对象]而不是对象

时间:2017-12-10 09:52:58

标签: forms reactjs redux react-redux javascript-objects

我有一个反应容器,里面有一个表格。表单包含三个单选按钮。我希望每个单选按钮输入的每个值都是从我的reducer中的一个对象数组中取出的对象。但是,当我在console.log中输入单选按钮的值时,我得到了这个:

  

[object Object]

我知道[object Object]是javascript中对象的默认toString表示,但是如何抓取实际对象以便我可以使用其中的信息?

这是我的代码:

class NoteInput extends React.Component {
    constructor(props) {
        super(props);

        this.state={
            selectedValue: null,
        }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e) {
        this.setState({selectedValue: e.target.value})
    }

    handleSubmit(e) {
        e.preventDefault();
        console.log(this.state.selectedValue);
    }

    render() {
        var inputs = this.props.locations.map((location, i) => {
            return (
                <div key={i}>
                    <input type="radio" id={i} name="location" value={location} />
                    <label htmlFor={'choice' + {i}}>{location.name}</label>
                </div>
            );
        });
        return (
            <div>
                <form onSubmit={this.handleSubmit} onChange={this.handleChange} >
                    {inputs}
                    <input type="submit" value="Submit" />
                </form>
            </div>
        );
    }
}

这是我的减速机:

export default function() {
    return [
        {name: 'Safa Park', locationLat: '25.184992', locationLong: '55.248140'},
        {name: 'Mercato', locationLat: '25.217054', locationLong: '55.253051'},
        {name: 'Burj Khalifa', locationLat: '25.197787', locationLong: '55.274862'}
    ]
}

1 个答案:

答案 0 :(得分:0)

您可以将stringify对象存储为radio button格式,其值为var inputs = this.props.locations.map((location, i) => { let strLoc = JSON.stringify(location); // stringify it return ( <div key={i}> <input type="radio" id={i} name="location" value={strLoc} /> <label htmlFor={'choice' + { i }}>{location.name}</label> </div> ); });

handleSubmit

handleSubmit(e) { e.preventDefault(); let strLoc = JSON.parse(this.state.selectedValue); //parse it back to json/object console.log(strLoc.name); } 中可以以json / object格式返回。

{{1}}

工作codesandbox demo