簡體   English   中英

如何在 ReactJS 中使用 filter() 從數組中刪除一項 - 函數無法正常工作

[英]How to remove one item from an array using filter() in ReactJS - function not working properly

我有一個函數可以從食譜對象數組中刪除一個食譜對象。

我實際上能夠刪除一個食譜(將其從名為 recipeList 的數組中刪除),但是當我點擊一個刪除按鈕時,它會刪除數組中的所有食譜。 我只想刪除我正在單擊的那個。

我很確定它與this.state.id 當我 console.log 時它出現未定義。 它應該指的是被刪除的食譜的鍵/ID。

任何人都知道問題可能是什么?

這是刪除功能:

handleDeleteRecipe = recipeId => {
// copy current list of items
const recipeList = [...this.state.recipeList];

//filter out item being deleted
const filteredList = recipeList.filter(recipe => this.state.id !== recipeId);
this.setState({recipeList: filteredList});
console.log('id: ' + this.state.id);

}

在初始狀態下,id 在一個名為 newRecipe 的對象中,它被設置為空:

this.state = {
  recipeList: [],
  newRecipe: {
    title: '',
    source: '',
    servings: '',
    id: ''
  }

我有一個添加新配方的功能,其中 id 設置為 1 到 1000 之間的隨機數。不知道這是否與它有任何關系。 它位於 newRecipe 對象的內部,然后該對象被添加到 recipeList 數組中。

handleAddNewRecipe = (title, source, servings, id) => {
const newRecipe = {
  title: title,
  source: source,
  servings: servings,
  id: (Math.floor(Math.random()* 1000))

這是數組中每個配方被映射並作為組件返回的地方。 它有一個設置為 recipe.id 的鍵。

{this.state.recipeList.map((recipe) => (
          <RecipeCardThumbnail
          title={recipe.title}
          servings={recipe.servings}
          key={recipe.id}
          handleDeleteRecipe={this.handleDeleteRecipe}
          />
        ))}

這是子組件的刪除按鈕:

onClick={() => this.props.handleDeleteRecipe(this.props.id)}>Delete</button>

顯然有一些我不理解的東西,但我不確定是什么。 任何幫助將非常感激!

編輯:我還嘗試了 console.logging recipeList 當我將我的食譜添加到數組並且 id 顯示得很好時。 所以我嘗試了 recipeList.id 並且所有的食譜都被刪除了同樣的問題。

再次編輯:我做了一個實驗,除了 console.log 之外,刪除了刪除函數中的所有內容。 我嘗試記錄recipeList並且對象中的所有內容都在那里。 但是當我記錄recipeList.id甚至recipeList.title時,它們都顯示為未定義。 我仍然不確定我做錯了什么......

this.state.id 將返回 undefined 因為你沒有直接在你的狀態下的 id 。 試試這個

handleDeleteRecipe = recipeId => {
// copy current list of items
const recipeList = [...this.state.recipeList];

//filter out item being deleted
const filteredList = recipeList.filter(recipe => recipe.id !== recipeId);
this.setState({recipeList: filteredList});

您的過濾器看起來不對,您從不使用要過濾的配方對象。 我認為它應該是recipeList.filter(recipe => recipe.id !== recipeId)

另外,您不需要先復制數組... Array.filter 無論如何都會返回一個新數組

暫無
暫無

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

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