【问题标题】:why am i getting [object object] instead of an object为什么我得到 [object object] 而不是 object
【发布时间】:2017-12-10 09:52:57
【问题描述】:

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

[对象对象]

我知道 [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'}
    ]
}

【问题讨论】:

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


【解决方案1】:

您可以将location 对象存储为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可以返回json/object格式。

handleSubmit(e) {
    e.preventDefault();
    let strLoc = JSON.parse(this.state.selectedValue); //parse it back to json/object
    console.log(strLoc.name);
  }

工作codesandbox demo

【讨论】:

  • 谢谢,当我现在控制台登录时,它起作用了:)