简体   繁体   English

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

[英]How do I add an element to array in reducer of React native redux?

How do I add elements in my array arr[] of redux state in reducer?如何在 reducer 的 redux 状态数组arr[]中添加元素? I am doing this-我在做这个——

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
    }
}

Two different options to add item to an array without mutation将项目添加到数组而不发生突变的两种不同选项

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

OR

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

push does not return the array, but the length of it ( docs ), so what you are doing is replacing the array with its length, losing the only reference to it that you had. push不返回数组,而是返回它的长度( docs ),所以你正在做的是用它的长度替换数组,失去对它的唯一引用。 Try this:试试这个:

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, action.newItem]
        }

        default:return state
     }
}

If you need to insert into a specific position in the array, you can do this:如果需要插入到数组中的特定位置,可以这样做:

case ADD_ITEM :
    return { 
        ...state,
        arr: [
            ...state.arr.slice(0, action.pos),
            action.newItem,
            ...state.arr.slice(action.pos),
        ],
    }

Since this question gets a lot of exposure:由于这个问题得到了很多曝光:

If you are looking for the answer to this question, there is a good chance that you are following a very outdated Redux tutorial .如果您正在寻找这个问题的答案,那么很有可能正在学习一个非常过时的 Redux 教程

The official recommendation (since 2019) is touse the official Redux Toolkit to write modern Redux code .官方推荐(自 2019 年起)是使用官方 Redux Toolkit 编写现代 Redux 代码

Among other things, that will eliminate string action constants and generate action creators for you.除此之外,这将消除字符串动作常量并为您生成动作创建者。

It will also employ methods that allow you to just write mutating logic in your Reducers created by createReducer or createSlice , so there is no need to write immutable code in Reducers in modern Redux in the first place.它还将使用允许您在由createReducercreateSlice创建的createSlice逻辑的createSlice ,因此首先无需在现代 Redux中的createSlice中编写不可变代码

Please follow the official Redux tutorials instead of third-party tutorials to always get the most up-to-date information on good Redux practices and will also show you how to use Redux Toolkit in different common scenarios.请遵循官方 Redux 教程而不是第三方教程,以始终获取有关良好 Redux 实践的最新信息,还将向您展示如何在不同的常见场景中使用 Redux Toolkit。

I have a sample我有样品

import * as types from '../../helpers/ActionTypes';

var initialState = {
  changedValues: {}
};
const quickEdit = (state = initialState, action) => {

  switch (action.type) {

    case types.PRODUCT_QUICKEDIT:
      {
        const item = action.item;
        const changedValues = {
          ...state.changedValues,
          [item.id]: item,
        };

        return {
          ...state,
          loading: true,
          changedValues: changedValues,
        };
      }
    default:
      {
        return state;
      }
  }
};

export default quickEdit;

If you need to add array one after another then you can use如果您需要一个接一个地添加数组,那么您可以使用

//initial state
const initialState = {
   array: [],
}

...
case ADD_ARRAY :
    return { 
        ...state,
        array: [...state.array, ...action.newArr],
    }
//if array = [1,2,3,4]
//and newArr = [5,6,7]
//then updated array will be -> [1,2,3,4,5,6,7]
...

This Spread syntax (...) iterates array element and store inside the array [ ], what you can simply do with " for loop " or with any loop.此Spread 语法(...) 迭代数组元素并存储在数组[ ] 中,您可以使用“ for循环”或任何循环简单地执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 REACT NATIVE REDUX如何在动作创建者收到的化简器中设置数组 - REACT NATIVE REDUX How to set an array in the reducer received by the action creator 如何在 React Native Redux 中实现以下内容 - Reducer - How to implement the following in React Native Redux - Reducer 如何在我的本机应用程序中仅使用redux persist仅用于一个reducer而不是导航reducer? - How can I use redux persist for only one reducer not for navigation reducer in my react native application? React Native Redux Reducer无法正常工作 - React Native Redux Reducer not working 无法将现有产品添加到 redux 减速器的购物车中,并使用本机反应 - cant add existing product in cart in reducer in redux with react native react-native redux-减速器更改数组元素 - react-native redux - reducer changing array elements React-Redux 减速器 - 添加到数组的第一个元素未定义 - React-Redux Reducer - First element added to an array is undefined React-Native和Redux:如何重用reducer处理多个组件 - React-Native and Redux: How to reuse reducer to handle multiple component 如何使用reducer中的redux特别在react-native中获取API? - How to fetch API in react-native specially using redux in the reducer? 如何在 React Native 中将数组中的数据添加到 object? - How do i add Data from an array to object in React Native?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM