【问题标题】:I have just started learning redux and I need some help how to remove an item from the state array我刚刚开始学习 redux,我需要一些帮助如何从状态数组中删除一个项目
【发布时间】:2019-06-13 09:11:31
【问题描述】:

我有一个歌曲列表,单击按钮时会显示详细信息。现在我想单击另一个按钮来删除显示的详细信息。该函数是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
});

【问题讨论】:

  • 您能否进一步输入您在有效负载中收到的内容以及您到底想要什么,您想要返回一个包含所有条目(歌曲)的新状态,除了点击的条目或其他内容?

标签: redux react-redux redux-form


【解决方案1】:

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

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 来执行不同的操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-20
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多