首页 > 解决方案 > 如何从 React 中的嵌套数组中根据其索引删除对象?

问题描述

我点击产品上的“删除”图标。我拉出他的索引并将其保存在状态中。示例:select: 1, index: 1. 如何设置this.setState删除嵌套在 arraycolors中的数组中的对象products。示例删除对象:

{
  a: 'orange'
} 

从数组colors中的数组products

this.state.select是产品中的项目,this.state.index是要删除的项目中的颜色

它在实际应用程序中的外观如何?给你的产品和颜色ID?我希望它是动态的。我点击产品,下载它的索引并删除

class App extends Component {
  constructor(){
    super();

    this.state {
      products: [  
            {
                colors: [{a:'black'}, {a:'orange'}, {a:'purple'}]
                desc: 'gfgfg'
            },
            {
                colors: [{a: 'yellow'}, {a: 'white'}, {a:'gray'}],
                desc: 'gfgfgfg'
            },
            {
                colors: [{a: 'pink'}, {a: 'brown'}, {a:'green'}],
                desc: 'gfgfgfg'
            }
        ],
        select: 1 //example
        index: 1 //example
    }

  }

  removeItem = () => {
    const { select, index } = this.state;

    if(index) {
      this.setState({
          products: [
            ...this.state.products[select].colors.slice(0, index),
            ...this.state.products[select].colors.slice(index + 1),
          ]
      });
    }
  };


  render () {

    return (
      <div>
        <ul>
            {
                this.state.products
                .map((product, index) =>
                    <Product
                        key={index}
                        index={index}
                        product={product}
                    />
                )
            }
        </ul>
          <Products

          />
      </div>
    )
  } 
}

标签: javascriptreactjsecmascript-6

解决方案


您需要将删除功能传递给Product组件,在Product组件中将选择和索引传递给removeItem功能。

修改你的删除项目,接受两个参数,selectindex.

removeItem = (select, index) => {

  const filtered = this.state.products[select].colors.filter(
    (color, i) => i !== index
  );

  this.setState(prevState => {
    return {
      select: select,
      index: index,
      products: [
        ...prevState.products.slice(0, select),
        Object.assign({}, prevState.products[select], { colors: filtered }),
        ...prevState.products.slice(select + 1)
      ]
    };
  });
};

将函数作为道具传递给Product组件。

<div>
  <ul>
    {this.state.products.map((product, index) => (
      <Product
        key={index}
        index={index}
        removeItem={this.removeItem}
        product={product}
      />
    ))}
  </ul>
</div>

在您的产品组件中,传递颜色的索引和选择。

<button onClick={() => removeItem(index, i)}>X</button>

演示

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>

<div id="root"></div>

<script type="text/babel">

class Product extends React.Component {
  render() {
    const { product, removeItem, index } = this.props;
    return (
      <div>
        <p>{product.desc}</p>
        <ul>
          {product.colors.map((color, i) => (
            <li>
              {color.a} <button onClick={() => removeItem(index, i)}>X</button>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: "React",
      products: [
        {
          colors: [{ a: "black" }, { a: "orange" }, { a: "purple" }],
          desc: "gfgfg"
        },
        {
          colors: [{ a: "yellow" }, { a: "white" }, { a: "gray" }],
          desc: "gfgfgfg"
        },
        {
          colors: [{ a: "pink" }, { a: "brown" }, { a: "green" }],
          desc: "gfgfgfg"
        }
      ],
      select: 1, //example
      index: 1 //example
    };
  }

    removeItem = (select, index) => {
      const filtered = this.state.products[select].colors.filter(
        (color, i) => i !== index
      );

      this.setState(prevState => {
        return {
          select: select,
          index: index,
          products: [
            ...prevState.products.slice(0, select),
            Object.assign({}, prevState.products[select], { colors: filtered }),
            ...prevState.products.slice(select + 1)
          ]
        };
      });
    };

  render() {
    return (
    <div>
      <ul>
        {this.state.products.map((product, index) => (
          <Product
            key={index}
            index={index}
            removeItem={this.removeItem}
            product={product}
          />
        ))}
      </ul>
    </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
</script>


推荐阅读