JSX:按字母顺序对对象排序

我有两个看起来像这样的函数:

  const compare = (direction: string) => {
    const alphabetize = (a, b) => {
      if (direction === "alpha") {
        if (a.name < b.name) {
          return -1;
        }
        if (a.name > b.name) {
          return 1;
        }
      } else if (direction === "reverseAlpha") {
        if (a.name > b.name) {
          return -1;
        }
        if (a.name < b.name) {
          return 1;
        }
      }
      return 0;
    };
  };

  const sortAlphabetically = () => {
    setState(state => ({
      ...state,
      items: items.sort(compare("alpha"))
    }));
  };

I need to be able to pass a string into the compare function somehow, that tells it which way to sort the letters (alphabetically, or reverse alphabetically).

But this method doesn't work, because alphabetize is never called this way. What am I missing?

谢谢!

评论