如何在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
    }
}

推荐答案

由于这个问题被大量曝光:

如果你正在寻找这个问题的答案,很有可能是you are following a very outdated Redux tutorial.

官方建议(自2019年起)增加到use the official Redux Toolkit to write modern Redux code.

除此之外,这将消除字符串动作常量,并为您生成动作创建者.

它还将使用一些方法,允许您只在由createReducercreateSlice创建的约简中编写变异逻辑,所以首先是there is no need to write immutable code in Reducers in modern Redux.

请遵循official Redux tutorials而不是第三方教程,以始终获得有关良好Redux实践的最新信息,并向您展示如何在不同的常见场景中使用Redux工具包.

相比之下,在现代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;

React-native相关问答推荐

如何在 React Native 中正确地将组件导入到我的导航器中?

在 React Native Paper 中更改 TextInput 的文本 colored颜色

如何在 React-Native 中创建检测自动位置的map

react-native StyleSheet 属性和选项列表

在根项目ReactNativeStarter中找不到任务installRelease

React Native - 当位置在Android上是绝对时视图消失

使用带有 react-native 的 WebView 设置用户代理

使用 Android NDK 在 C 或 C++ 中创建 react-native Native Module?

如何使用 React Navigation 使 TabNavigator 按钮推送模态屏幕

React Native:自定义字体在 Android 和 iOS 上呈现不同

React Native 元素搜索栏边界线未清除

如何在 React Native 中使用 Jest

Unexpected token on "export default const"

React Native 元素,未生成 index.ios.js 或 index.android.js

动态改变 React Native Flat List 中的列数

如何在react-native中绘制虚线边框样式

如何在 React Native 的 MapView 中设置标记

React-Native Invariant Violation:元素类型无效

React native - 以编程方式判断是否启用了远程 JS 调试

如何允许 react-native 启用对 JSX(扩展)文件的支持