使用setState将对象数组添加到对象自身数组中

时间:2018-09-25 14:51:41

标签: javascript reactjs

如何为对象数组添加新行?

class App extends React.Component {
  state = {
    inputs: [{
      name: 'firstname',
      value: ''
    },{
      name: 'lastname',
      value: ''
    }]
  }
  addRow = () => {
    //what to do here
  }
  render() {
    return(
      <div>
        {this.state.inputs.map(input => <input placeholder={input.name} type="text" />)}
         <button onClick={this.addRow}>add row</button>
        </div>
    )
  }
}

https://codesandbox.io/s/mz8v7v4y99

在这种情况下,我必须使用lodash的deepClone吗?

3 个答案:

答案 0 :(得分:2)

您不一定需要复制。可以在数组中重用相同的对象:

this.setState({inputs: [...this.state.inputs, {name: 'foo', value: ''}]});

答案 1 :(得分:1)

看看我创建的沙箱。 https://codesandbox.io/s/xj1zz7m5wq

在这里,我使用了散布运算符来复制现有输入数组并将数据插入该数组中。

addRow = () => {
    const inputs = [...this.state.inputs];
    inputs.push({
      name: "dummyname",
      value: ""
    });
    this.setState({
      inputs
    });
  };

答案 2 :(得分:0)

首先,您必须将状态设置为以下

并添加新行,您可以使用传播运算符

const newState = [...this.state.inputs, newRow];

我重写了您的代码,以便您可以看一下并尝试理解它

class App extends React.Component {
  state = {
    inputs: [
      {
        firstname: 'Ibrahim',
        lastname: 'Doe'
      },
      {
        firstname: 'Mohammed',
        lastname: 'Jon'
      }
    ],
    inputFirstname: '',
    inputLastame: ''
  };

  handleOnChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  addRow = e => {
    e.preventDefault();
    const newRow = {
      firstname: this.state.inputFirstname,
      lastname: this.state.inputLastame
    };
    const newState = [...this.state.inputs, newRow];
    this.setState({
      inputs: newState,
      inputFirstname: '',
      inputLastame: ''
    });
  };

  render() {
    return (
      <form>
        {this.state.inputs.map(input => (
          <div key={input.firstname}>
            <input placeholder={input.firstname} type="text" />
            <input placeholder={input.lastname} type="text" />
          </div>
        ))}
        <input
          onChange={this.handleOnChange}
          placeholder="firstname"
          type="text"
          name="inputFirstname"
          value={this.state.inputFirstname}
        />
        <input
          onChange={this.handleOnChange}
          placeholder="lastname"
          type="text"
          name="inputLastame"
          value={this.state.inputLastame}
        />
        <button onClick={this.addRow}>add row</button>
      </form>
    );
  }
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>