簡體   English   中英

將項目添加到 Reducer 中的空數組中會給出錯誤“類型錯誤:傳播不可迭代實例的嘗試無效”。

[英]Add Items into Empty array in Reducer give Error 'TypeError: Invalid attempt to spread non-iterable instance.'

我試圖在 reducer 中聲明任何空數組並嘗試在其中動態添加一些對象。但是當我嘗試在其中添加新項目時出現此錯誤。'TypeError: Invalid trial to spread non-iterable instance.'It意味着您沒有任何要在其中添加新項目的數組?怎么可能。這是我的減速器狀態。

const initialState = {
  
  recentSearches: [],
 
};

這是我的功能啟動

const handleItem = async (item) => {
    let recent = [...recentSearches];
    recent.push(item);
    new Promise((rsl, rej) => {
      addSearchItem(recent, rsl, rej);
    })
      .then((res) => {
        navigation.navigate('SearchDetail', {text: item.name});

        // console.log('Zaid ----->', res);
      })
      .catch((res) => {
        console.log(res);
      });
  };

這是減速器的動作

export const addSearchItem = (data, rsl, rej) => {
  return (dispatch) => {
    try {
      dispatch({
        type: ADD_SEARCH,
        recentSearches: data,
      });
      rsl();
    } catch (err) {
      rej();
    }
  };
};

這是這種情況

case ADD_SEARCH:
      return {
        ...state,
        recentSearches: action.recentSearches,
      };

您可以通過這種方式不可變地更新 redux 中的數組

return {
...state,
recentSearches:state.recentSearches.concat(item),
}

我希望這將有助於更多關注這個https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns

當您嘗試在減速器中復制未定義的數組時會發生此錯誤。 例如:

const newList = [...state.someList];

在這種情況下,'someList' 未定義或不是數組。 確保您的拼寫或您使用的是正確的數組。

尚未修復 上面提供的解決方案

暫無
暫無

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

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