简体   繁体   中英

add array of object into self array of object using setState

How can I add new row for my array of object?

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

do I have to use lodash's deepClone in this case?

You don't necessarily need to make copies. Reusing the same objects in your array is acceptable:

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

Take a look at the sandbox I have created. https://codesandbox.io/s/xj1zz7m5wq

Here is I have used spread operator to make copies of existing inputs array and inserted data into that array.

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

first, you have to set the state same as below

and to add a new row you can use spread operator

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

I rewrite your code so you can look at it and try to understand it

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM