简体   繁体   English

REDUX:如何从我的阵列中删除相关项目?

[英]REDUX: How can I delete related item from my array?

I am working on a project in React using Redux.我正在使用 Redux 在 React 中开发一个项目。 I am trying to delete an item.我正在尝试删除一个项目。 However, it added an array to my array.但是,它向我的数组添加了一个数组。 How can I delete it?我怎样才能删除它? Here is my code:这是我的代码:

import ActionTypes from "../constants/ActionTypes";

const initialState = {
  myCities: [],
  aCity: {},
  getCityById: {},
};

export const WeatherReducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case ActionTypes.GETBY_CITYNAME:
      return {
        ...state,
        aCity: payload,
        myCities: [...state.myCities, payload],
      };
    case ActionTypes.GETCITYBYID:
      return {
        ...state,
        getCityById: payload,
        myCities: [], //first I tried to it empty, not works at all and I also tried without it
        myCities: [ 
          ...state.myCities,
          initialState.myCities.filter((item) => item.id !== payload.id), //Then I tried to find related item, choose it and add all objects to my array without related item
        ],
      };
    default:
      return state;
  }
};

I also added my delete stuff:我还添加了我的删除内容:

const HandleDelete = (cityId) => {
  dispatch(GetCityById(cityId, apiKEY));
};

Thanks for your effort谢谢你的努力

The .filter() method already returns a new array, so there is no need to put it inside of another array here .filter()方法已经返回了一个新数组,所以这里没有必要把它放在另一个数组里面

myCities: [ 
  ...state.myCities,
  initialState.myCities.filter((item) => item.id !== payload.id)
],

The above creates a new array [] , and then puts all the elements in state.myCities into that new array using the spread syntax ( ... ) .上面创建了一个新数组[] ,然后使用扩展语法 ( ... )state.myCities所有元素放入该新数组中。 Then, it adds a new element, which is the filtered array of initialState.myCities.filter() .然后,它添加一个新元素,即initialState.myCities.filter()的过滤数组。 Instead, as .filter() returns an array only containing the items your callback returned true for, you can directly use that array as the new value for myCities:相反,由于.filter()返回一个仅包含您的回调为其返回true的项目的数组,您可以直接使用该数组作为myCities:的新值myCities:

myCities: initialState.myCities.filter((item) => item.id !== payload.id)

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

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