简体   繁体   中英

How to add an object in the array of objects in react js

I am new to the react . Here , what I have tried.

onaddRow(e, id) {
        const addData = this.props.lowData;
        const tempObj = {
            id: 'L1',
            technologyId: 0,
            technology: '',
            type: '',
            numberOfQuestions: ''
        }
        addData.push(tempObj);
    }

this.props.lowData is an array of the objects . So, I want to add an object in this .

So, I tried the following way but it was not working , can any one suggest me how can I do this ?

You can get updated array usign (spread) ... also.

onaddRow(e, id) {  
    const tempObj = {
        id: 'L1',
        technologyId: 0,
        technology: '',
        type: '',
        numberOfQuestions: ''
    }
    const addData = [...this.props.lowData, tempObj ];
    console.log(addData)
}

//as you asked in comment. if you want to remove item from array you can do like this.

let updatedArrray = yourArray.filter(i => {
  return i.id != passYourIdHere;
});
console.log(updatedArrray);

so here we are returning all other object's except matching one, finally collecting in updatedArrray.

通过使用addData.push(),您可以将对象有效地添加到数组中(如果props.lowData确实是对象数组),但是鉴于您位于React环境中,因此应在此之后执行。setState({lowData:addData })以触​​发组件的重新呈现。

React uses one-way data flow (from parent to children). In your example you received data from parent in props. For adding new object you must pass callback from parent which will add it to the parent state.

Child component:
onAddRow(e, id) {  
    const tempObj = {
        id: 'L1',
        technologyId: 0,
        technology: '',
        type: '',
        numberOfQuestions: ''
    }
    this.props.onAddRow(tempObj)
}

Parent:

onAddRow = (newObj) => {
 this.setState({
   lowData: [...this.state.lowData, newObj]
 })
}
render() {

<ChildComponent data={this.state.lowData} onAddRow={this.onAddRow} />

}

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