简体   繁体   中英

Reactjs, how to instanciate object from array, and update render

I'm struggling with reactjs for no reason. I'm a little confused about the magic behind and I'm not able to perform a simple operation of adding object / removing object from an array and display it.

I my parent, I have a method which on click append a new element:

  appendNewPma(){
    var newPma = this.state.pma.slice();
    newPma.push(PmaType1);
    this.setState({pma:newPma})
  }

then my render method is like that:

  render() {
    return (
      <div>
        <a className="waves-effect waves-light btn" onClick={this.appendNewPma}>new</a>
        {this.state.pma.map((Item, index) => (
          <Item
            key       = {index}
            ref       = {"pma" + index.toString()}
            onDelete  = {() => this.onDelete(index)}
            title     = {index}/>
        ))}
      </div>
    );
  }

Append work fine, but my array doesn't contain an object to display but rather a magical function that I don't understand.

But when I try to delete an object:

  onDelete(idx){
    console.log(idx);
    var pma = this.state.pma.slice();
    pma.splice(idx, 1);
    this.setState({pma:pma})
  }

When I delete from the array, no matter what index I will remove, it will only remove the last object. I know my code is not ok, but I have no idea how you can render element for an array of object (here my array is list of function constructor). It will work better if I could get a straight ref to my object. Of course, I tryed to removed from the ReactDom, but was complening I was not updating from the parent...

I just want a simple array push/pop pattern with update.

Thanks for your help

Try below code. hope so it solve your issue.

  addToArray = (event) => {
    this.state.pma.push({"name ": "xyz"});
    this.setState(
      this.state
    )
  }
  removeFromArray =(index) => {
    var updatedArr = this.state.pma.splice(index, 1);
    this.setState({arr : updatedArr})
  }

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