如何在 React native redux 的 reducer 中向数组添加元素?

新手上路,请多包涵

如何在reducer中redux状态的数组 arr[] 中添加元素?我正在这样做——

 import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
    arr:[]
}

export default function userState(state = initialUserState, action)
{
    console.log(arr);
    switch (action.type)
    {
        case ADD_ITEM:
            return {
                      ...state,
                      arr: state.arr.push([action.newItem])
                   }

        default:
            return state
    }
}

原文由 coderzzz18 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 818
2 个回答

由于这个问题得到了很多曝光:

如果您正在寻找这个问题的答案,那么 您很有可能正在关注一个非常过时的 Redux 教程

官方推荐(自 2019 年起)是 使用官方 Redux Toolkit 编写现代 Redux 代码

除其他外,这将消除字符串动作常量并为您生成动作创建者。

它还将采用允许您在由 createReducercreateSlice 创建的 Reducer 中编写变异逻辑的方法,因此 无需在现代 Redux 中的 Reducers 中编写不可变代码 第一名。

请遵循 官方 Redux 教程 而不是第三方教程,以始终获取有关良好 Redux 实践的最新信息,还将向您展示如何在不同的常见场景中使用 Redux Toolkit。

相比之下,在现代 Redux 中,这看起来像

const userSlice = createSlice({
  name: "user",
  initialState: {
    arr:[]
  },
  reducers: {
    // no ACTION_TYPES, this will internally create a type "user/addItem" that you will never use by hand. You will only see it in the devTools
    addItem(state, action) {
      // you can use mutable logic in createSlice reducers
      state.arr.push(action.payload)
    }
  }
})

// autogenerated action creators
export const { addItem } = slice.actions;

// and export the final reducer
export default slice.reducer;

原文由 phry 发布,翻译遵循 CC BY-SA 4.0 许可协议

将项目添加到数组而不发生突变的两种不同选项

case ADD_ITEM :
    return {
        ...state,
        arr: [...state.arr, action.newItem]
    }

或者

case ADD_ITEM :
    return {
        ...state,
        arr: state.arr.concat(action.newItem)
    }

原文由 yadhu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题