通过ReactJs在对象数组中查找最大值

时间:2019-04-17 07:20:43

标签: reactjs

我有一系列包含数组(json文件)中某些对象的数据,将通过fetch请求显示。有一个renderMaxTotal()函数必须为我提供最大数量的数据在json文件的所有数据的totalcom中,但是它显示了当前页面中totalcom中的最大数量,并且通过转到另一页面,renderMaxTotal()的数量将被更改。

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        library: null,
        perPage: 20,
        currentPage: 1,
        maxPage: null,
    };
}
componentDidMount() {
    fetch('/json.bc', {
        method: 'get',
    })
        .then(response => response.text())
        .then(text => {
            let Maindata = JSON.parse(text.replace(/\'/g, '"'))
            this.setState(state => ({
                ...state,
                data: Maindata
            }), () => {
                this.reorganiseLibrary()
            })
        }).catch(error => console.error(error))
}
reorganiseLibrary = () => {
    const { perPage, data } = this.state;
    let library = data;
    library = _.chunk(library, perPage);
    this.setState({
        library,
        currentPage: 1,
        maxPage: library.length === 0 ? 1 : library.length
    })
}

// 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 <div className="nodata">No Result</div>
    }
    return library[currentPage - 1].sort((a, b) => a.total - b.total).map((item, i) => (
        <div className="item">
            <span>{this.renderTotalcom(item)}</span>
        </div>
    ))
}
// handle render of library
renderMaxTotal = () => {
    const { library, currentPage } = this.state;
    if (!library || (library && library.length === 0)) {
        return <div className="nodata">No Result</div>
    }
    return Math.max(...library[currentPage].map(item => item.totalCom))
}
render() {
    const { library, currentPage, perPage, maxPage } = this.state;
    return (
        <div>
            <span className="max">{this.renderMaxTotal()}</span>
            {this.renderLibrary()}
            <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>
    )
}
renderTotalcom(element) {
    console.log(typeof element.totalCom)
    return element.totalCom
  } 
}
ReactDOM.render(<App />, document.getElementById('Result'))

如果我将renderMaxTotal()更改为此: Math.max(...library[0].map(item=>item.totalCom)) 它将显示第一页的最大值,而转到另一页则不会改变。 如果我将renderMaxTotal()更改为此: Math.max(...library.map(item=>item.totalCom)) 将会是NaN。 我如何在整个页面中拥有最大数量的totalcom

1 个答案:

答案 0 :(得分:0)

下面的代码将获取每页的最大值,并将其与当前的最大值进行比较。

// handle render of library
renderMaxTotal = () => {
  const { library } = this.state;
  if (!library || (library && library.length === 0)) {
      return <div className="nodata">No Result</div>
  }
  return library.reduce((acc,lib)=>{
      const libMax = Math.max(...lib.map(item => item.totalCom))
      return libMax > acc ? libMax : acc
  },0)
}