简体   繁体   English

React.js,如何实例化数组中的对象并更新渲染

[英]Reactjs, how to instanciate object from array, and update render

I'm struggling with reactjs for no reason. 我无缘无故地在React。 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... 当然,我尝试从ReactDom中删除,但是很高兴我没有从父级进行更新...

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})
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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