If 语句不起作用,但三元语句会起作用。为什么?

If statement won't work, but the ternary will. Why?

我想知道为什么注释掉的const sortingMethod不起作用,而active的sortingMethod却起作用。

第一个是 'normal' if 语句,而另一个是三元运算符,如果我没记错的话。不是一样的东西,只是写法不同吗?

import { useState } from "react";

import Player from "./Player";

export default function Scoreboard() {
  const initPlayerScores = [
    {
      id: 1,
      name: "Dexter",
      score: 33,
    },
    {
      id: 2,
      name: "Noodles",
      score: 112,
    },
    {
      id: 3,
      name: "Greg",
      score: 3,
    },
    {
      id: 4,
      name: "Ron",
      score: 12,
    },
  ];

  const [players, setPlayers] = useState(initPlayerScores);

  const [sortBy, setSortBy] = useState("score");

  const sortByScore = (playerA, playerB) => playerA.score - playerB.score;

  const sortByName = (playerA, playerB) =>
    playerA.name.localeCompare(playerB.name);

  // const sortingMethod = () => {
  //   if (sortBy === "name") {
  //     return sortByName;
  //   } else {
  //     return sortByScore;
  //   }
  // };

  const sortingMethod = sortBy === "name" ? sortByName : sortByScore;

  const playersSorted = [...players].sort(sortingMethod);

  const changeSorting = (event) => {
    setSortBy(event.target.value);
  };

  return (
    <div>
      <h1>The Scoreboard</h1>
      Sort by{" "}
      <select onChange={changeSorting}>
        <option value="name">Name</option>
        <option value="score">Score</option>
      </select>
      {playersSorted.map((player) => (
        <Player key={player.id} name={player.name} score={player.score} />
      ))}
    </div>
  );
}

我认为@deceze 的意思是您需要评估 sortingMethod 中的 sortByName 和 sortByScore 函数。下面的代码将起作用:

const sortingMethod = (playerA, playerB) => {
    if (sortBy === "name") {
        return sortByName(playerA, playerB);
    } else {
        return sortByScore(playerA, playerB);
    }
}