首页 > 解决方案 > 为什么在 Redux 动作触发后 react 不会设置状态?

问题描述

我试图在 redux 触发后在组件中本地设置状态,但它不起作用,我在这里做错了什么?

    <TableCell
        onClick={() => {
          if (dropDownLocation === "allLocations") {
            overlayDisplay("open");
          } else {
            console.log(values.rescheduleDate);
            getReservationsByDate(row.reservation_date); // Redux action
            getStaffMember(row.staff_name); // Redux action
            setValues((prevState) => {
              return {
                ...prevState,
                rescheduleDate: true, // always logged as false
              };
            });
          }
        }}
      >CLICK</TableCell>

标签: reactjsreduxreact-reduxreact-hooksredux-thunk

解决方案


默认情况下,Redux 的 action 是同步调度的,所以这里可以使用 async-await 来做异步操作。

 <TableCell
    onClick={async () => {
      if (dropDownLocation === "allLocations") {
        overlayDisplay("open");
      } else {
        console.log(values.rescheduleDate);
        await getReservationsByDate(row.reservation_date); // Redux action
        await getStaffMember(row.staff_name); // Redux action
        await setValues((prevState) => {
          return {
            ...prevState,
            rescheduleDate: true, // always logged as false
          };
        });
      }
    }}
  >CLICK</TableCell>

推荐阅读