如何在 ReactJs 中对数据进行排序

玛雅人

我有Items数据,我试图isis显示按数组中的cost字段排序的数组值。这是我的代码:costtableroomnameDoubletype2

杰森:

    {
        "index": 1,
        "id": "5e3961face022d16a03b1de9_1023632_1004876",
        "costtable": [
            {
                "roomname": "Single",
                "room_id": "1023632_479490,1004876_385485",
                "family": [
                    {
                        "title": "adult 1",
                        "cost": 3.7568000,
                        "unit": "10",
                        "type": "2"
                    }
                ]
            }
        ]
    },
    {
        "index": 2,
        "id": "5e3961face022d16a03b1de9_1088496_1005362",
        "costtable": [
            {
                "roomname": "Double",
                "room_id": "1088496_447339,1005362_415279",
                "family": [
                    {
                        "title": "adult 1",
                        "cost": 5.6868000,
                        "unit": "10",
                        "type": "2"
                    }
                ]
            }
        ]
    },
    {
        "index": 3,
        "id": "5e3961face022d16a03b1de9_1141859_1005529",
        "costtable": [
            {
                "roomname": "Single",
                "room_id": "1141859_74888,1005529_870689",
                "family": [
                    {
                        "title": "adult 1",
                        "cost": 5.9586000,
                        "unit": "10",
                        "type": "2"
                    }
                ]
            }
        ]
    }
]

代码:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            Items: [],
            library: null,
            perPage: 20,
            currentPage: 1,
            maxPage: null,

        }
    }
    componentDidMount() {
        fetch('/json', {
            method: 'GET',
        })
            .then(response => response.text())
            .then(text => {
                let Maindata = JSON.parse(text.replace(/\'/g, '"'))
                let CostSort = Maindata.map(a => {
                    return this.renderSort(a)
                })
                Maindata.sort((a, b) => a.CostSort - b.CostSort);
                this.setState(state => ({
                    ...state,
                    Items: Maindata
                }), () => {
                    this.reorganiseLibrary()
                })
            }).catch(error => console.error(error))

    }
    reorganiseLibrary = () => {
        const { perPage, Items } = this.state;
        let library = Items;
        library = _.chunk(library, perPage);
        this.setState({
            library,
            currentPage: 1,
            maxPage: library.length === 0 ? 1 : library.length
        });
    };

    renderSort(element) {
        let indents = []
        let lenFamilies = element.costtable.length
        for (let i = 0; i < lenFamilies; i++) {
            if (element.costtable[i].roomname.indexOf('Double') > -1) {
                for (let j = 0; j < element.costtable[i].family.length; j++) {
                    if (element.costtable[i].family[j].type == 2) {
                        indents.push(element.costtable[i].family[j].cost)
                        break;
                    }
                }
                break;
            }
        }
        return (indents)

    }

    // Previous Page
    previousPage = event => {
        this.setState({
            currentPage: this.state.currentPage - 1
        });
    };
    // Next Page 
    nextPage = event => {
        this.setState({
            currentPage: this.state.currentPage + 1
        });
    };



    // handle per page
    handlePerPage = (evt) =>
        this.setState({
            perPage: evt.target.value
        }, () => this.reorganiseLibrary());

    // handle render of library
    renderLibrary = () => {
        const { library, currentPage } = this.state;
        if (!library || (library && library.length === 0)) {
            return '';
        }
        return library[currentPage - 1].map((item, i) => (
            <div className="item-list">
                {item.index}
            </div>
        ));
    };
    render() {
        const { library, currentPage, perPage, maxPage } = this.state;
        return (
            <div>
                <div className="wrapper-data">
                    {this.renderLibrary()}
                </div>
                <div class="clr"></div>
                <ul id="page-numbers">
                    <li className="nexprevPage">
                        {currentPage !== 1 && (
                            <button onClick={this.previousPage}><span className="fa-backward"></span></button>
                        )}
                    </li>
                    <li className="controlsPage active">{this.state.currentPage}</li>
                    <li className="restControls">...</li>
                    <li className="controlsPage">{this.state.maxPage}</li>
                    <li className="nexprevPage">
                        {(currentPage < maxPage) && (<button onClick={this.nextPage}><span className="fa-forward"></span></button>
                        )}
                    </li>
                </ul>
            </div>
        );
    }

}
ReactDOM.render(<App />, document.getElementById('Content'));

这段代码没有给我任何错误,但以未排序的格式显示值。我该如何排序?

新代码

  Maindata.sort((a, b) => {
            let lenFamilies = a.costtable.length
            for (let i = 0; i < lenFamilies; i++) {
                if( a.costtable[i].roomname.indexOf('Double') > -1){
                    for (let j = 0; j < a.costtable[i].family.length; j++) {
                        if( a.costtable[i].family[j].type == 2){

                        a.costtable[i].family[j].cost- b.costtable[i].family[j].cost
                        }
                    }
                }
            }
        }
哈桑·陶基尔

我不明白您用来排序的确切公式,但是您在排序之前所做的事情是错误的。

在你的 componentDidMount

let CostSort = Maindata.map(a => { return this.renderSort(a) })

这将一个数组返回到一个被调用的变量中CostSort,并且不会MainData以任何方式产生影响

但是,稍后您会这样做。

Maindata.sort((a, b) => a.CostSort - b.CostSort);

对于第一次迭代,这将比较 Maindata[0] 和 Maindata[1]。请注意,在任何一个对象中都没有 CostSort,因此您正在执行undefined - undefinedwhich is 的操作NaN因此不会发生排序。

我建议您只使用该sort函数并在那里对两个值进行比较。

Maindata.sort((a, b) => {
 // Do your calculation here

 if(a should be before b) {
    return -1;
  } else {
    return 1;
  }
}

PS js 中变量的约定是camelCase和 not PascalCase所以,Maindata他应该mainData

编辑:这是一个适用于上述情况的简单排序实现,您可以根据您的完整用例对其进行扩展。

Maindata.sort((a, b) => {
  let lenFamilies = a.costtable.length;
  for (let i = 0; i < lenFamilies; i++) {
    if (
      a.costtable[i].roomname.includes("Double") &&
      !b.costtable[i].roomname.includes("Double")
    ) {
      return -1;
    }
    if (
      !a.costtable[i].roomname.includes("Double") &&
      b.costtable[i].roomname.includes("Double")
    ) {
      return 1;
    }
    if (a.costtable[i].roomname.indexOf("Double") > -1) {
      for (let j = 0; j < a.costtable[i].family.length; j++) {
        if (a.costtable[i].family[j].type == 2) {
          a.costtable[i].family[j].cost - b.costtable[i].family[j].cost;
        }
      }
    }
  }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章