React - 如何向对象添加动态键/值对?

时间:2017-04-12 16:53:02

标签: javascript reactjs object

我正在尝试使用appendInput()函数将动态键/值对添加到初始对象。

初始对象:

constructor(props) {
super(props);
this.state = {
  milestonesValues : {
    milestone0: "dssdsad",
    milestone1: "",
    milestone2: "",
    milestone3: "",
  }
};

}

渲染方法:

render(){
return(
  <div>
    <main className="content">
      <form onSubmit={this.onSubmit}>
        <div className="input-wrap">
          <label>{'What are the basic steps?'}
            {Object.keys(this.state.milestonesValues).map( (milestone, index) =>
              <input
                key={milestone}
                placeholder={`${index+1}.` }
                type="text"
                name={milestone}
                value={this.state.milestonesValues[milestone]}
                onChange={this.handleInputChange} />
              )}
          </label>
          <button onClick={ () => this.appendInput() }>
            {"+ ADD MILESTONE"}
          </button>
        </div>
       </form>
     </main>
   </div>
);

appendInput()函数:

  appendInput() {
var objectSize = Object.keys(this.state.milestonesValues).length;
var newInput = `milestone${objectSize}: "",`;

console.log(newInput);
this.setState({
  milestonesValues: this.state.milestonesValues.concat([newInput])
});

}

我无法将新生成的键/值添加到该初始对象。

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

您可以使用computed expression完成您想要的任务(我不确定您是否尝试过这样做)。所以你的appendInput函数看起来应该是这样的:

&#13;
&#13;
appendInput() {
  var objectSize = Object.keys(this.state.milestonesValues).length;
  var newInput = Object.assign({}, 
this.state.milestonesValues, {['milestone'+ objectSize]: ''});
  this.setState({
    milestonesValues: newInput)
  });
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用此:

appendInput() {
    var milestonesValues = Object.assign({}, this.state.milestonesValues);

    var objectSize = Object.keys(milestonesValues).length;
    var newInput = `milestone${objectSize}`;

    milestonesValues[newInput] = '';

    this.setState({ milestonesValues });
}

检查此示例:

let data = {
  milestonesValues : {
    milestone0: "dssdsad",
    milestone1: "",
    milestone2: "",
    milestone3: "",
  }
};

function addelement(){
   var milestonesValues = Object.assign({}, data.milestonesValues);

    var objectSize = Object.keys(milestonesValues).length;
    var newInput = `milestone${objectSize}`;

    milestonesValues[newInput] = '';

    data.milestonesValues = milestonesValues;
}

addelement();

console.log(data.milestonesValues);

答案 2 :(得分:0)

var newInput = Object.assign({},
this.state.products.map(function(addNewfield){ addNewfield[val]= '' }));
this.setState({ products: newInput })