简体   繁体   中英

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. I have the following code:

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:

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

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:

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. The Reducer code deals with the menu array, which is an array of objects:

在此处输入图像描述

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. To do this, I have to copy the array first, make the modifications and then reassign the state to this new array.

I have tried to console.log() the state to see what it is in my Reducer function. When I click on the up-arrow div in category-arrows.component.jsx , the INCREASE_CATEGORY_RANK action is dispatched. 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. Any insights are appreciated.

To copy an array without mutating the original (assuming this is a reducer case):

// 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)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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