reactjs - 根据日期字段mongodb按排序顺序显示记录

时间:2017-08-02 03:21:55

标签: reactjs

从mongodb获取记录并在reactjs中显示它。我想在日期字段上按排序顺序呈现这些记录。请建议我。

我没有使用mongoes。只有Reactjs和mongodb。

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

render() {
return (<tbody>{ this.props.items.map((item) => <SearchResults key={ item.id 
} item={ item } open={ this.props.open } />) }</tbody>);
}
}

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

render() {
return (
<tr onClick={ this.handleOpen } style={{color: 'blue',fontsize: '12',cursor: 
'pointer'}}>
<td>{ this.props.item.OrderNumber }</td>
<td>{ this.props.item.Assignee }</td>
<td>{ this.props.item.Status }</td>
<td>{ this.props.item.OrderDate }</td>
<td>{ this.props.item.CreatedDate }</td>
</tr>
);
}

2 个答案:

答案 0 :(得分:0)

如果您正在以JSON格式接收数据,则将其转换为数组,然后根据所需的数据字段进行排序。您可以使用下划线,lodash类库来利用随时可用的方法。

编辑: 请参阅我的另一个答案,其中显示了如何将对象转换为数组并对其进行排序。

React render model in sorted order on a field

答案 1 :(得分:0)

您可以将条目排序为新数组并渲染这些...

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

        this.renderItems = this.renderItems();
    }

    renderItems() {
        // using slice to avoid mutation
        const items = this.props.items.slice().sort((a, b) => {
            return b.date - a.date; // or some other logic to determine if a and b should be swapped
        });

        items.map(item =>
            <SearchResults
                key={item.id}
                item={item}
                open={this.props.open}
            />
        );

    }

    render() {
        return (
            <tbody>
                {this.renderItems()}
            </tbody>
        );
    }
}

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

    render() {
        return (
            <tr
                onClick={this.handleOpen}
                style={{
                    color: "blue",
                    fontsize: "12",
                    cursor: "pointer"
                }}
            >
                <td>
                    {this.props.item.OrderNumber}
                </td>
                <td>
                    {this.props.item.Assignee}
                </td>
                <td>
                    {this.props.item.Status}
                </td>
                <td>
                    {this.props.item.OrderDate}
                </td>
                <td>
                    {this.props.item.CreatedDate}
                </td>
            </tr>
        );
    }
}