我刚刚开始学习redux,我需要一些帮助如何从状态数组中删除项目

时间:2019-06-13 09:11:31

标签: redux react-redux redux-form

我有一个歌曲列表,单击该按钮可显示详细信息。现在,我想单击另一个按钮以删除显示的详细信息。该函数是removeDescriptionReducer。我正在显示我的减速器文件。

reducers.js

import { combineReducers } from 'redux';

const songsReducer = () =>{
  return [
    { title: 'No Scrubs', duration: '4:05'},
    { title: 'Macarena', duration: '3:55'},
    { title: 'All Stars', duration: '1:28'},
    { title: 'I want it that way', duration: '2:05'},

  ];
};



const selectedSongReducer = (selectedSong=null, action) => {

  if(action.type === 'SONG_SELECTED'){
    return action.payload;
  }

  return selectedSong;

}



const removeDescriptionReducer = (removeDescription=null, action) => {

    if(action.type === 'REMOVE_DESCRIPTION'){
    alert (action.payload);
  }

  return removeDescription;

}

export default combineReducers({
  songs: songsReducer,
  selectedSong: selectedSongReducer,
  removeDescription: removeDescriptionReducer
});

1 个答案:

答案 0 :(得分:0)

根据问题标题,您要从状态中删除一项:

return state.filter(elem => elem.title == 'xyx')

return state.filter(elem => elem.title == payload.title)

这将返回除符合指定条件的元素以外的所有元素

其中xyz可以是有效载荷中的标题

在您的代码中:

const removeDescriptionReducer = (removeDescription = null, action) => {

  if (action.type === 'REMOVE_DESCRIPTION') {
    alert(action.payload);
    return songsReducer.filter(song => song.title == action.payload.title);
  }

  return removeDescription;

}

此外,您也不想让您失望,但您的减速器必须像这样:

const songs = () => {
  return [{
      title: 'No Scrubs',
      duration: '4:05'
    },
    {
      title: 'Macarena',
      duration: '3:55'
    },
    {
      title: 'All Stars',
      duration: '1:28'
    },
    {
      title: 'I want it that way',
      duration: '2:05'
    },

  ];
};


const songsReducer = (state = songs, action) => {
  switch(action.type) {
    case 'ALL_SONGS':
      return state;
    case 'SONG_SELECTED':
      return action.payload;
    case 'REMOVE_DESCRIPTION':
        return state.filter(song => song.title == action.payload.title);
      default:
        return state;
  }
}

,因此您无需创建不同的reducer即可执行不同的操作。