将数据从index.tsx传递到Next.js中的其他页面

xvw2m8pv  于 2023-03-12  发布在  其他
关注(0)|答案(1)|浏览(138)

我在App.tsx中有一个react应用程序,代码如下

function App() {
  let date = new Date();
  // storing full name of all months in array
  const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];

  const [currentMonth, SetCurrentMonth] = useState<string>(
    months[date.getMonth()]
  );
  const [currentYear, SetCurrentYear] = useState<number>(date.getFullYear());

  const changeMonth = (val: string) => {
    // if clicked icon is previous icon then decrement current month by 1 else increment it by 1
    if (val === "prev") {
      if (currentMonth === "January") {
        SetCurrentMonth(months[11]);
        SetCurrentYear((currentYear) => currentYear - 1);
      } else {
        SetCurrentMonth(months[months.indexOf(currentMonth) - 1]);
      }
    } else {
      if (currentMonth === "December") {
        SetCurrentMonth(months[0]);
        SetCurrentYear((currentYear) => currentYear + 1);
      } else {
        SetCurrentMonth(months[months.indexOf(currentMonth) + 1]);
      }
    }
  };

  return (
    <div className="App">
      <Routes>
        <Route
          path="/"
          element={
            <>
              <ViewSelector />
              <Summary
                monthNumber={months.indexOf(currentMonth)}
                month={currentMonth}
                year={currentYear}
                onClick={changeMonth}
              />
            </>
          }
        />
        <Route
          path="/calendar/:player"
          element={
            <>
              <ViewSelector />
              <Calendar
                date={date}
                monthNumber={months.indexOf(currentMonth)}
                month={currentMonth}
                year={currentYear}
                onClick={changeMonth}
              />
            </>
          }
        />
        <Route
          path="/manage"
          element={
            <>
              <ViewSelector />
              <Manage />
            </>
          }
        />
      </Routes>
    </div>
  );
}

export default App;

在React中,我们使用RoutesRoute创建路由,并将某些状态变量(currentMonthcurrentYear ...)传递给特定路由。
现在,我尝试在Nextjs中重写这个应用程序,但是我无法弄清楚如何将状态变量(currentMonthcurrentYear ...)从index.tsx传递到其他页面(因为它们是各自文件夹中的单独index.tsx文件)
有人能给我带路吗?

e37o9pze

e37o9pze1#

这是一个非常基本的例子,关于如何使用next传递参数。这就是你要找的吗?或者我没有理解你的问题?

索引.jsx

import Link from "next/link"

export default function Index() {
  const date = new Date()

  return (
    <Link
      href={{
        pathname: "/other",
        query: { date: date },
      }}
    >
      <a>About page</a>
    </Link>
  )
}

其他.jsx

import { useRouter } from "next/router"

export default function Other() {
  const router = useRouter()

  const {
    query: { date },
  } = router
  return <div>{date.toString()}</div>
}

相关问题