【问题标题】:sort items in state alphabetically按字母顺序对状态中的项目进行排序
【发布时间】:2021-05-22 03:43:45
【问题描述】:

我有一个基于类的 React 组件,它使用状态和渲染结果中的项目。这是简短的 sn-p 我如何做到这一点:

class Menu extends Component {
    constructor(props) {
        super(props);
        this.state = {
            items: props.items.edges,
            someItems: props.items.edges,
        }
    }

    render() {
        if (this.state.items.length > 0) {
            return (
                <div className="container">
                    <div className="row">
                        {this.state.someItems.map(({ node }) => {
                            return (
                                <div key={node.id}>
                                    <div>
                                        render some data
                                    </div>
                                </div>

                            )
                        })}
                    </div>
                </div>
            );
        }
    }
}

数据作为数组中的对象接收,如下所示:

我的问题是是否可以在呈现之前按字母顺序对这些项目进行排序?最好的方法是什么?

【问题讨论】:

  • 是的,您可以按字母顺序排序。

标签: reactjs


【解决方案1】:

最好的方法是在将项目设置为状态之前对其进行排序。您可以使用内置的Array.prototype.sort 方法对项目进行排序。您可以使用String.prototype.localeCompare 按字母顺序比较字符串。

我不知道您的数据的预期结构,所以这里是一个通用的解决方案。

class App extends React.Component {
    constructor(props) {
        super(props);

        // Make a copy so as not to modify the original array directly
        const sortedCopy = [...props.items];

        sortedCopy.sort((a, b) => a.name.localeCompare(b.name));

        this.state = {
            items: sortedCopy,
        };
    }

    render() {
        return (
            <div>
                {this.state.items.map((item) => (
                    <p key={item.id}>
                        <div>Item - {item.name}</div>
                    </p>
                ))}
            </div>
        );
    }
}

// Example items prop is out of order
const items = [
    { id: 0, name: "C" },
    { id: 1, name: "B" },
    { id: 2, name: "A" },
    { id: 3, name: "D" },
];

ReactDOM.render(<App items={items} />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

【讨论】:

  • 非常感谢阿比尔。这就说得通了。与您的数据相比,我的数据更加嵌套。在对其进行排序之前,我将如何映射它,这里是我的数组中的一个项目的示例:const sortedCopy = [this.props.items.edges[0].node.title]
  • 我找到了上述评论的“解决方案”,我的数据非常嵌套,所以仍然试图让我的头脑围绕它。我找到了另一篇解释这一点的帖子。以下是文章供参考:stackoverflow.com/questions/38364400/index-inside-map-function
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
相关资源
最近更新 更多