ReactJS - sorting - TypeError: 0 is read only

时光总嘲笑我的痴心妄想 提交于 2020-08-27 06:39:24

问题


I'm trying to sort an object before mapping it in reactjs, but every single time I do, I keep getting the TypeError: 0 is read only. I noticed that on load the props are empty, but even when I was trying to check the length of the array and only apply sort when it's higher than 0, or when the array exists to be precised, it would still happen. The moment I try to sort anything, it just stops working.

I would like to be able to sort these via different criteria in the future, but so far I can't even go through regular sorting on render...

I have the below:

ToysList.jsx

import React, { Component } from 'react';
import PropTypes from 'prop-types';


class ToysList extends Component {
  constructor (props) {
    super(props);
    this.state = {};
}


render () {
    var toys = this.props.toys;
    var arr = toys.sort((a,b) => parseFloat(a.price) - parseFloat(b.price));

    return (
        <div>
            <div key="list">
               { arr.map((toy, index) => (
                    <div key={toy.id}>
                        {toy.name}:<br/>
                        Quantity: {toy.quantity}<br/>
                        Price: {toy.price}<br/>
                        Rating: {toy.rating}
                    </div>
                )) }
            </div>
        </div>
    );
}
}

ToysList.propTypes = {
toys: PropTypes.arrayOf(
    PropTypes.shape({
        id: PropTypes.string,
        name: PropTypes.string,
        quantity:PropTypes.number,
        price:PropTypes.number,
        rating:PropTypes.number,
    }),
).isRequired,
};


export default ToysList;

I'd be grateful for any hint with these. Thanks


回答1:


That could be because sort mutates the array it works on (it sorts in-place).

If this.props.toys is immutable then it would throw that error.

Create a copy of the array and sort that.

var toys = this.props.toys.slice();
// var toys = Array.from(this.props.toys);
// var toys = [...this.props.toys];
var arr = toys.sort((a,b) => parseFloat(a.price) - parseFloat(b.price));


来源:https://stackoverflow.com/questions/49278578/reactjs-sorting-typeerror-0-is-read-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!