简体   繁体   English

React-Redux:从减速器 function 中的 state 复制一个数组,以便您可以修改它

[英]React-Redux: Copying an array from the state in Reducer function so that you can modify it

I am working on a React application and I am using Redux to store the state.我正在开发一个 React 应用程序,我正在使用 Redux 来存储 state。 I have the following code:我有以下代码:

menu.reducer.js: menu.reducer.js:

import { INCREASE_CATEGORY_RANK, DECREASE_CATEGORY_RANK } from './menu.types';

const INITIAL_STATE = []


export default (state = INITIAL_STATE, action) => {
    switch (action.type) {

        case INCREASE_CATEGORY_RANK: {
            console.log("Printing the state");
            console.log(state);
            return state.map(category => {
                if (category._id === action.payload._id) {
                    const oldrank = category.rank;
                    return {
                        ...category,
                        rank: oldrank + 1
                    }
                } else {
                    return category;
                }
            })
        }
        case DECREASE_CATEGORY_RANK: {
            return state.map(category => {
                if (category._id === action.payload._id && category.rank !== -1) {
                    const oldrank = category.rank;
                    return {
                        ...category,
                        rank: oldrank - 1
                    }
                } else {
                    return category;
                }
            })
        }
        default:
            return state;
    }
}

menu.types.js: menu.types.js:

export const INCREASE_CATEGORY_RANK = "INCREASE_CATEGORY_RANK";
export const DECREASE_CATEGORY_RANK = "DECREASE_CATEGORY_RANK";

menu.actions.js: menu.actions.js:

import { apiUrl, apiConfig } from '../../util/api';
import { INCREASE_CATEGORY_RANK, DECREASE_CATEGORY_RANK } from './menu.types';

export const getMenu = () => async dispatch => {
    const response = await fetch(`${apiUrl}/menu`);
    if (response.ok) {
        const menuData = await response.json();
        dispatch({ type: GET_MENU, payload: menuData })
    }
}

export const increaseCategoryRank = category => dispatch => {
    dispatch({ type: INCREASE_CATEGORY_RANK, payload: category })
}

export const decreaseCategoryRank = category => dispatch => {
    dispatch({ type: DECREASE_CATEGORY_RANK, payload: category })
}

category-arrows.component.jsx:类别箭头.component.jsx:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { increaseCategoryRank, decreaseCategoryRank } from '../../redux/menu/menu.actions';
import './category-arrows.styles.scss';

class CategoryArrows extends Component {

    render() {

        const { category, increaseCategoryRank, decreaseCategoryRank } = this.props;

        return (
            <div class="arrows-container">
                <div class="up-arrow" onClick={() => this.props.increaseCategoryRank(category)}></div>
                <div class="category-rank">
                    <p>{category.rank}</p>
                </div>
                <div class="down-arrow" onClick={() => this.props.decreaseCategoryRank(category)}></div>
            </div>
        )
    }
}

export default connect(null, { increaseCategoryRank, decreaseCategoryRank } )(CategoryArrows);

For my Reducer function, the initial state is retrieved from a database.对于我的减速器 function,从数据库中检索初始 state。 The Reducer code deals with the menu array, which is an array of objects: Reducer 代码处理menu数组,它是一个对象数组:

在此处输入图像描述

I want to sort this menu array with respect to the rank property value, and also swap elements in the array based on certain conditions.我想根据rank属性值对这个menu数组进行排序,并根据某些条件交换数组中的元素。 To do this, I have to copy the array first, make the modifications and then reassign the state to this new array.为此,我必须先复制数组,进行修改,然后将 state 重新分配给这个新数组。

I have tried to console.log() the state to see what it is in my Reducer function.我试图 console.log() state 看看它在我的减速器 function 中有什么。 When I click on the up-arrow div in category-arrows.component.jsx , the INCREASE_CATEGORY_RANK action is dispatched.当我单击category-arrows.component.jsx中的up-arrow div 时,将调度INCREASE_CATEGORY_RANK操作。 When I check the Console, I get the following:当我检查控制台时,我得到以下信息:

在此处输入图像描述

I am not sure how to copy the menu array from the state in my Reducer function so that I can make the modifications that I want to and then reassign this array to the state.我不知道如何从我的减速器 function 中的 state 复制菜单数组,以便我可以进行我想要的修改,然后将此数组重新分配给 Z9ED39E2EA931586B6A985A6942EF75 Any insights are appreciated.任何见解都值得赞赏。

To copy an array without mutating the original (assuming this is a reducer case):要复制一个数组而不改变原始数组(假设这是一个 reducer 案例):

// make a copy of the original
const updatedArray = [...state.menu]

// find the object you want to modify (this is a generic example)
let selectedItem = updatedArray.findIndex((element) => {
  return element.id === action.payload._id
}

// make your modification (let's pretend you wanted to update the name property)
updatedArray[selectedItem].name = 'Changed Name'

// merge the original state and set the menu property to the updatedArray
return {
  ...state,
  menu: updatedArray
}

Is this the problem you're trying to solve (copying original state and modifying it)?这是您要解决的问题吗(复制原始 state 并进行修改)?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM