最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort mapped list with Lodash on ReactJS - Stack Overflow

programmeradmin3浏览0评论

I have an array:

people = [
  {
    name: "Kyle",
    _id: "2"
  },
  {
    name: Susan,
    _id: "1"
  }
]

I have a mapped list as such:

return (
  <ul>
    {people.map( (person) => {
      return (
        <li>
          <span>{person.name}</span>
          <span>{person.id}</span>
        </li>
       )
    })}
  </ul>
)

This is all working well, but how can I sort them, say based on "name"? I tried to use the [_.sortBy][1] but couldn't figure out how it would fit to the context of React and map function. Using lodash, or underscore's _.sortBy would be appreciated.

Thanks!

I have an array:

people = [
  {
    name: "Kyle",
    _id: "2"
  },
  {
    name: Susan,
    _id: "1"
  }
]

I have a mapped list as such:

return (
  <ul>
    {people.map( (person) => {
      return (
        <li>
          <span>{person.name}</span>
          <span>{person.id}</span>
        </li>
       )
    })}
  </ul>
)

This is all working well, but how can I sort them, say based on "name"? I tried to use the [_.sortBy][1] but couldn't figure out how it would fit to the context of React and map function. Using lodash, or underscore's _.sortBy would be appreciated.

Thanks!

Share Improve this question asked Nov 5, 2015 at 10:44 EmoEmo 6201 gold badge9 silver badges28 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 8

In _.sortBy you can pass the name of the field that will be used for sorting your collection, read more about _.sortBy

var Component = React.createClass({
    getInitialState() {
        return {
            people: _.sortBy([
                { name: "Kyle", _id: 2}, 
                { name: "Susan", _id: 1}
            ], '_id')
        }
    },

    sortBy(field) {
        this.setState({ 
            people: _.sortBy(this.state.people, field) 
        });
    },

    render: function() {
        var peopleList = this.state.people.map( (person, index) => {
            return (<li key={index}>
                <span>{person.name}</span>
                <span>{person.id}</span>
            </li>);        
        })

        return <div>
            <a onClick={this.sortBy.bind(this, '_id')}>Sort By Id</a> | 
            <a onClick={this.sortBy.bind(this, 'name')}>Sort By Name</a>
            <ul>{peopleList}</ul>
        </div>;
    }
});

Example

You can use the sortBy like this:

_.sortBy(<array name here>, '<key here>')

Try

return (
    <ul>
        {_.sortBy(people, 'name').map( (person) => {
            return (
                <li>
                    <span>{person.name}</span>
                    <span>{person.id}</span>
                </li>
            )
        })}
    </ul>
)

You need to import it first

import sortBy from "lodash/sortBy";

And then you can use it like

const arr = [{id: 2}, {id: 0}];
sortBy(arr, "id");
发布评论

评论列表(0)

  1. 暂无评论