reactjs 如何根据状态Map不同的数组?

xqkwcwgp  于 2023-01-25  发布在  React
关注(0)|答案(1)|浏览(159)

我现在有一个切换按钮。如果为假,它应该隐藏列中的红色卡片(延迟作业)。如果为真,应该显示所有作业。但是它不工作。状态改变,但没有重新渲染发生。

const App = () => {
  const [showLateJobs, setShowLateJobs] = useState(true);
  const [user, setUser] = useState("default");
  const multipleUsersArray = [...otherUser, ...AllJobs];

  let toOrderArray =
    user === "default"
      ? AllJobs.filter((job) => job.category === "to_order")
      : multipleUsersArray.filter((job) => job.category === "to_order");

  let toOrderArrayNoLate =
    user === "default"
      ? AllJobs.filter((job) => job.category === "to_order" && job.late != true)
      : multipleUsersArray.filter(
          (job) => job.category === "to_order" && job.late != true
        );

  const [toOrderState, setToOrderState] = useState(
    showLateJobs ? toOrderArray : toOrderArrayNoLate
  );

  return (
    <>
      <Toggle
        defaultChecked={true}
        onChange={(e) => {
          if (!e.target.checked) {
            setShowLateJobs(false);
            console.log("toggled");
          } else {
            setShowLateJobs(true);
          }
        }}
      />

      <Column>
        {toOrderState.map((job, index) => (
          <JobCard
            job_number={job.jobNumber}
            time={job.time}
            cardHeight={layout === "extended" ? "150px" : "50px"}
            layout={layout}
            backgroundColor={job.late && "#D64045"}
            displayLateIcon={job.late && "block"}
          />
        ))}
      </Column>
    </>
  );
};
nsc4cvqm

nsc4cvqm1#

问题是你把计算值设置成state作为初始值,因为你从来没有调用setToOrderState(...),所以state值永远不会改变。
如果你想从现有的状态派生新的状态,你可以使用一个memo钩子

// Define these outside your component
// so they're not re-initialised every render
const DEFAULT_USER = "default";
const CATEGORY_FILTER = "to_order";

const multipleUsersArray = [...otherUser, ...AllJobs];

const filterPredicate =
  (includeLate) =>
  ({ category, late }) =>
    category === CATEGORY_FILTER && (includeLate || !late);
// And these inside your component
const [showLateJobs, setShowLateJobs] = useState(true);
const [user, setUser] = useState(DEFAULT_USER);

const toOrderState = useMemo(
  () =>
    (user === DEFAULT_USER ? AllJobs : multipleUsersArray).filter(
      filterPredicate(showLateJobs)
    ),
  [user, showLateJobs] // hook dependencies
);

相关问题