简体   繁体   中英

ReactJS: Sorting an array of data from the state that is passed to a component as a props

I am working on a React application and I am using Redux to store the state. I have the following data.

menu.data.js:

export default [
    {
        "_id": "c0daac6ab8954a40606dd8b81d24a0ef",
        "name": "Entree",
        "rank": "0",
        "items": [
            {
                "title": "Curry Puffs",
                "price": 14,
                "_id": "615caa7dd573bcf84781c9e4382b520d"
            },
            {
                "title": "Spring Rolls",
                "price": 12,
                "_id": "542f711856b7854b71d9862797620e23"
            },
            {
                "title": "Tandoori Cauliflower",
                "price": 20,
                "_id": "f0c0f2fa02e392ad4e74dfaaf6068fb1"
            }
        ]
    },
    {
        "_id": "934aeba1e96e6d6a4207cd5ba207b52a",
        "name": "Lunch",
        "rank": "1",
        "items": [
            {
                "title": "Spaghetti",
                "price": 20,
                "_id": "db414e2b9951ed621fbf6fb40df36ee3"
            },
            {
                "title": "Spaghetti",
                "price": 20,
                "_id": "253592733a8f7835f390d3d9ed8bda95"
            },
            {
                "title": "Spaghetti",
                "price": 20,
                "_id": "a22741f27a346cda93d3cf752e371779"
            }
        ]
    }
]

I have the following component:

import React from 'react';
import { connect } from 'react-redux';

import MenuCategory from '../../components/menu-category/menu-category.component'
import NewCategoryButton from '../../components/new-category-button/new-category-button.component';

import './menu.styles.scss';

const MenuPage = props => {

    console.log("Printing the menu");
    console.log(props.menu);

    const menuItems = props.menu;
    menuItems.sort((a,b) => (a.rank < b.rank) ? 1 : -1);

    console.log("After sorting the items");
    console.log(menuItems);

    return (
        <div className='menu-page'>
            {props.menu ? props.menu.map(category => <MenuCategory key={category._id} {...category} />) : null}
            {props.currentUser ? <NewCategoryButton /> : null}
        </div>
    )
}

const mapStateToProps = state => ({
    currentUser: state.user.currentUser,
    menu: state.menu
})

export default connect(mapStateToProps)(MenuPage);

In the above code, I am sorting the objects from menu.data.js in descending order with respect to the rank. The data from menu.data.js is passed to the MenuPage component as a props.

Through sorting the menu data, the Lunch object will come before the Entree object in the menuItems array.

However, I have noticed that when I console.log() props.menu and the menuItems array, they are both the same, despite the fact that I have only sorted menuItems .

在此处输入图像描述

As a result, when I render the data, the items in the Lunch category are displayed before the items in the Entree category, even though I am mapping through props.menu and not menuItems . When I remove the code that assigns props.menu to menuItems and then sorts menuItems , the Entree items are displayed before the Lunch items. Ie

    import React from 'react';
    import { connect } from 'react-redux';

    import MenuCategory from '../../components/menu-category/menu-category.component'
    import NewCategoryButton from '../../components/new-category-button/new-category-button.component';

    import './menu.styles.scss';

    const MenuPage = props => {    

        return (
            <div className='menu-page'>
                {props.menu ? props.menu.map(category => <MenuCategory key={category._id} {...category} />) : null}
                {props.currentUser ? <NewCategoryButton /> : null}
            </div>
        )
    }

    const mapStateToProps = state => ({
        currentUser: state.user.currentUser,
        menu: state.menu
    })

    export default connect(mapStateToProps)(MenuPage);

I am not sure why this is occurring. Any insights are appreciated.

This happens because you have assigned the array by reference like:

const a = [1, 3, 2]
const b = a

Now, if you sort b , then a is also automatically sorted like:

 const a = [1, 3, 2] const b = a b.sort() console.log(a) console.log(b)

Only way to resolve that would be to create a clone of the array a and then assign that to b like:

 const a = [1, 3, 2] const b = [...a] // clone array using spread syntax b.sort() console.log(a) console.log(b)

Now, you can see only b is sorted and a is still the same.

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