我希望将组件设置为仅当用户想要编辑条目的内容时才可见. 问题在于标题中所述的错误.

我使用setState将布尔值设置为@toggle, setToggle,然后在此基础上有条件地呈现组件UpdateReserve(位于TSX的底部).每个渲染的项目都应该有S自己的按钮来编辑.

这里的其他解决方案也无济于事.也许我忽略了一些东西.首先要感谢你的帮助.

这是文件的第一部分:

function tables({ days, closedDays }: HomeProps) {

  /**
   * SET STATES HERE
   * @param toggle handles visibilty of UpdateReservation
   * @param selectedDay is the currently selected day
   */
  const [toggle, setToggle] = useState<boolean>(initToggle);
  const [selectedDay, setSelectedDay] = useState<string>(initDate);

  // ID OF ITEM
  let currentId: string = "";

  /**
   * TOGGLE VISIBILITY OF UpdateReservation
   * @param id is the id of the toggled reservation
   */
  function toggleEdit(id: string) {
    setToggle(!toggle);
    currentId = id;
  };

  //tRPC
  const { mutateAsync: addItem } = trpc.admin.bookReservation.useMutation();
  const { data: reservations, refetch } = trpc.admin.getReservations.useQuery();
  const { mutateAsync: updateReservation } = trpc.admin.updateReservation.useMutation();
  const { mutateAsync: deleteReservation } = trpc.admin.deleteReservation.useMutation();

  /**
   * FUNCTIONS TO SELECT DAY
   * INCREASE OR DECREASE BY 1 DAY
   */
  function setToday() {
    setSelectedDay(initDate);
  }

  function increaseDay() {
    const date: Date = addDays(parseISO(selectedDay), 1);
    setSelectedDay(formatISO(date));
  };

  function decreaseDay() {
    const date: Date = subDays(parseISO(selectedDay), 1);
    setSelectedDay(formatISO(date));
  };

  /**
   * USE EFFECTS
   */
  useEffect(() => {
    setSelectedDay
    console.log("useEffect, selectedDay");
  }, [selectedDay]);

  useEffect(() => {
    setToggle
    console.log("useEffect, setToggle");
    console.log("currentId", currentId);
  }, [toggle])

  /**
   * HANDLE DELETION OF RESERVATION
   * @param id id of reservation
   */
  const handleDelete = async (id: string) => {
    await deleteReservation({ id });
    refetch();
  };

  /**
   * Filters reservations before rendering to only show reservations for the selected date
   */
  const filterTablesByDate = reservations?.filter((reservation) => {

    const formatDate: string | undefined = reservation.date.split('T')[0]
    const formatSelectedDay: string | undefined = selectedDay.split('T')[0]

    if (formatDate === formatSelectedDay) {
      return reservation;
    };

  });

  /**
   * filteredTablesbyDate will get sorted from earliest to latest booking for the corresponding day
   */
  const sortedTables = filterTablesByDate?.sort((a: any, b: any) => {
    const aDate: Date = new Date(a.date);
    const bDate: Date = new Date(b.date);

    const aTime: number = aDate.getTime();
    const bTime: number = bDate.getTime();

    return aTime - bTime;
  });

这个是渲染的TSX:

return (
    <>
      <div className="flex flex-col items-center justify-around p-24 text-[#2E3A59]">
        <h1 className='mt-8 text-[50px] font-bold'>Bookings</h1>
        <div>
          <Link href="/booking" className="m-2 flex items-center h-fit w-fit border-2 border-[#FFA500] py-1 px-4 gap-[12px] text-[20px] font-bold hover:scale-110 hover:bg-[#7EC699] hover:text-[#2E3A59] duration-300">
            MAKE RESERVATION
          </Link>
          <div>
            <div className='m-2'>
              <p className='text-lg font-bold m-2'>Reservations for <strong>{format(parseISO(selectedDay), 'do MMM yyyy', { locale: de })}</strong></p>

              <div className='flex flex-row'>
                <button
                  onClick={decreaseDay}
                >
                  -1 Day
                </button>
                <button
                  onClick={setToday}
                >
                  TODAY
                </button>
                <button
                  onClick={increaseDay}
                >
                  +1 Day
                </button>
              </div>
            </div>
            <p className='text-lg font-bold m-2'>Total reservations: {index}</p>
            <div className='m-6 p-6 mb-12 w-[90vw] h-fit flex flex-row flex-wrap items-start flex-center'>

              {sortedTables?.map((reservation) => (
                <div key={reservation.id} className="m-1 p-1 border h-fit w-fit border-black">
                  <p className="font-bold">NAME: {reservation.name} {reservation.surname}</p>
                  <div className='w-full bg-black h-[2px]' />
                  <p><strong>email: </strong>{reservation.email}</p>
                  <p><strong>phone: </strong>{reservation.phone}</p>
                  <p><strong>Time: </strong>{format(parseISO(reservation.date), 'do MMM yyyy', { locale: de })},{format(parseISO(reservation.date), 'kk:mm', { locale: de })}</p>
                  <p><strong>Seats: </strong>{reservation.seats}</p>
                  <p className='max-w-[280px]'><strong>Message: </strong>{reservation.message}</p>
                  <div className='w-full bg-black h-[2px]' />
                  <div className='flex flex-row justify-around'>
                    <button
                      onClick={() => handleDelete(reservation.id)}
                      className='text-xs text-red-500 border-red-500 border-2 p-1 m-1 rounded-md hover:scale-110 duration-300 hover:text-white hover:bg-red-500'
                    >
                      Delete
                    </button>

                    <button
                      onClick={() => toggleEdit(reservation.id)}
                      className='text-xs text-green-500 border-green-500 border-2 p-1 m-1 rounded-md hover:scale-110 duration-300 hover:text-white hover:bg-green-500'
                    >
                      Edit
                    </button>


                  </div>
                </div>
              ))}

            </div>
            <div>

              {toggle && (
                <UpdateReservation days={days} closedDays={closedDays} id={currentId} toggleEdit={toggleEdit} />
              )}

            </div>

          </div>
        </div>
      </div>
    </>
  )
};

export async function getServerSideProps() {
  const days = await prisma.day.findMany();
  const closedDays = (await prisma.closedDay.findMany()).map((d) => formatISO(d.date));
  return { props: { days, closedDays } };
};

export default tables;

我try 了几个我在这里找到的解决方案,但都没有真正起到作用.我总是收到标题中提到的相同错误.

推荐答案

我只想指出,这个useEffect将在循环中运行,因为它必须在依赖数组中切换,并且在useEffect中,您将再次设置状态setTogger,这将再次设置切换并重新呈现组件.

UseEffect(()=>;{ 设置切换 Console.log("useEffect,setTogger"); Console.log("URRENTID",URRENTID); },[切换])

相反,试试这个

UseEffect(()=>;{ 设置切换 Console.log("useEffect,setTogger"); Console.log("URRENTID",URRENTID); }、[])

Javascript相关问答推荐

React native在不首次加载时渲染的挂钩比上一次渲染期间渲染的挂钩更多

如何使图像逐渐/平稳地响应(先减少宽度,然后减少高度)

回归函数不会迭代到foreach中的下一个元素

Flisk和JS错误:未捕获的Syntax错误:意外的令牌'<'

使用print This时, map 容器已在LeafletJS中初始化

vanillajs-datepicker未设置输入值,日期单击时未触发更改事件

通过使用100%间隔时间来代表我们还剩多少时间来倒计时

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

类型脚本中只有字符串或数字键而不是符号键的对象

yarn安装一个本地npm包,以便本地包使用main项目的node_modules(ckeditor-duplicated-modules错误)

拖放仅通过 Select 上传

为什么!逗号和空格不会作为输出返回,如果它在参数上?

Reaction Native中的范围滑块

material UI按钮组样式props 不反射

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

环境值在.js文件/Next.js中不起作用

扩展类型的联合被解析为基类型

未加载css colored颜色 ,无法将div设置为可见和不可见

Jest toHaveBeenNthCalledWith返回当前设置的变量值,而不是调用时的值

如何修复错误&语法错误:不能在纯react 项目中JEST引发的模块&之外使用导入语句?