【问题标题】:Redux: Updating State of an array using ReduxRedux:使用 Redux 更新数组的状态
【发布时间】:2022-01-14 18:44:41
【问题描述】:

问题来了:

在 manageFriends.js 中,编写一个名为 manageFriends 的函数,该函数接受先前的状态和一个动作作为其参数。在这里,初始状态应该是一个对象,其键是friends,设置为一个空数组。 这一次,reducer 应该能够处理两个动作,“friends/add”和“friends/remove”。添加朋友时,该操作将包括分配给具有名称、家乡和 id 键的对象的朋友键。

 action = {
   type: "friends/add",
   payload: {
     name: "Chrome Boi"
     homewtown: "NYC",
     id: 1
   }
 } 

当我们的 reducer 收到“friends/add”时,它应该返回一个新状态,并将这个朋友对象添加到朋友数组中。

这是我在 js 浏览器控制台中运行的代码

function manageFriends(state = {friends: []},
    action = {
        type: "friends/add",
        payload: {
            name: 'Mac Miller',
            hometown: 'Arizona',
            id: 1
        },
        payload: {
            name: 'Kirk Franklin',
            hometown: 'ATL',
            id: 1
        },
        type: "friends/remove",
        payload: 1,
    }){
    switch (action.type) {
        case 'friends/add':
            return {friends: [...state.freinds, action.payload]}
    case 'friends/remove':
            return {
                friends: state.friends.filter((friend) => friend.id !=action.payload)
            };
        default:
            return state;
    }
}

manageFriends(state, action)

当我运行减速器时,我仍然得到一个空数组。

{friends: Array(0)}
friends: Array(0)
length: 0
[[Prototype]]: Array(0)
[[Prototype]]: Object

我发现这个示例有助于使用 switch case 语句。但我认为问题在于行动。

我之前测试过这个功能 这对我来说非常好

let state = {presents : true}

function managePresents(state, action){
    action = {
        type: "presents/increase",};
    switch (action.type) {
        case 'presents/increase':
            return { presents: !state.presents}
        default:
            return state;
    }
}

managePresents(state, action)

结果:{presents: false}

关于如何使用 redux 更新数组(朋友)状态的任何想法?

【问题讨论】:

  • freinds !== friends

标签: javascript arrays redux


【解决方案1】:

问题是你试图用一个简单的函数做太多事情。 Action 应该有两个关键参数,TYPE 和 PAYLOAD,而不是多条吸在一起的语句。

如果您尝试一次运行函数 Once(manageFriends ) 会有所帮助。或者尝试使用循环/forEach 如果需要多次运行。

const initialState = { friends: [] };

let action = {
  type: 'friends/add',
  payload: {
    name: 'Mac Miller',
    hometown: 'Arizona',
    id: 1,
  },
};

function manageFriends(state, action) {
  switch (action.type) {
    case 'friends/add':
      return { friends: [...state.friends, action.payload] };
    case 'friends/remove':
      return {
        friends: state.friends.filter((friend) => friend.id != action.payload),
      };
    default:
      return state;
  }
}



manageFriends(initialState, action);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2019-07-28
    相关资源
    最近更新 更多