簡體   English   中英

如何根據對象的索引從 React 中的嵌套數組中刪除對象?

[英]How delete an object based on its index from a nested array in React?

我點擊了產品上的“刪除”圖標。 我拉出他的索引並將其保存在狀態中。 示例: select: 1index: 1 如何設置this.setState以刪除數組products嵌套在數組colors中的對象。 示例刪除對象:

{
  a: 'orange'
} 

來自陣列products陣列colors

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

您需要將 remove 函數傳遞給Product組件,在Product組件中將 select 和 index 傳遞給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)
      ]
    };
  });
};

將函數作為 prop 傳遞給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>

只需使用Array.filter()創建一個不包含特定元素的新數組。 因此,該 desc 的新顏色數組是:

this.state.products[select].colors.filter( color => color.a !== 'orange' )

這將保留a不是橙色的所有顏色。 請記住,數組是從零開始的,因此您的selectindex都應從 0 開始。

如果您不想存儲實際索引,請改用 desc。

所以如果selectgfgfg而不是數組索引,你可以這樣做:

 const 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' } ], selected_product: 'gfgfg', color: 'orange' }; const setState = update => Object.assign( state, update ); console.log( 'before update' ); console.log( JSON.stringify( state.products[0] )); setState({ products: state.products.map( product => { if ( product.desc === state.selected_product ) { product.colors = product.colors.filter( color => color.a !== state.color ); } return product; }) }); console.log( 'after update' ); console.log( JSON.stringify( state.products[0] ));

使用索引顯然可以完成相同的邏輯,但這可能會導致更長的代碼。 如果一切都必須完全不可變,則可能必須更新某些代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM