next.js 如何通过状态或 prop 使用路由器推从导航下一个js13

uklbhaso  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(128)

我以前使用过'next/router'的路由器,但我阅读了版本13的文档,它说我需要把它改成'next/navigation'。但是如何将用户数据传递给路由器推送。这是我的代码片段

'use client';

import { FormEvent, useEffect, useState } from "react";
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs';
import { useRouter } from 'next/navigation';

export default function formLogin() {
    const [user, setUser] = 
        useState<{email: string; password: string}>({
            email: '',
            password: ''
    });
    const router = useRouter();
    
    useEffect(() => {
        setUser({
            email: user.email, 
            password: user.password
        });
    }, []);

    const supabase = createBrowserSupabaseClient();

    const login = async (e: FormEvent) => {
        e.preventDefault();
        
        const { data, error } = await supabase.auth.signInWithPassword({
            email: user.email,
            password: user.password,
        })
        
        router.push('/dashboard');
    }
}
5gfr0r5j

5gfr0r5j1#

您将不得不通过查询参数/ URL参数传递您的数据,如下所示

router.push(`/dashboard/?email=${email}&password=${password}`)

然后在你的页面.tsx中,通常默认是一个服务器组件,页面组件有两个props,即paramssearchParams。更多信息及其类型定义here
举个例子,我在一个示例应用程序中输入了一个搜索栏,用户可以在其中输入国家名称以从国家REST API获取国家信息。
search-bar.tsx

"use client";

import { useRouter } from "next/navigation";
import { ChangeEvent, useState } from "react";
const SearchBar = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const router = useRouter();

  const handleSearch = (e: ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(e.target.value);
    router.push(`/?search=${e.target.value}`)
  };

  const debouncedSearch = debounce(handleSearch, 500)

  return (
    <div className="flex gap-1 items-center">
      <img
        src="/search-magnifying-glass-svgrepo-com.svg"
        alt="search icon"
        width={20}
        height={20}
      />
      <input
        type="text"
        name="search-country"
        placeholder="Search for a country..."
        className="url"
        onChange={(e) => debouncedSearch(e)}
      />
    </div>
  );
};

export default SearchBar;

我的page.tsx文件

import SearchBar from "./search-bar";

interface Params {
  slug: string
}

interface SearchParams {
  [key: string]: string | string[] | undefined
}

export default async function Home({params, searchParams}: {params: Params, searchParams: SearchParams}) {
  const countries: Array<any> = !searchParams.search ? await getCountriesData() : await getCountryByName(searchParams.search as string)
  return (
    <main className="flex flex-col gap-2 overflow-x-hidden">
      <header>
        <Navbar />
      </header>
      <div className="flex justify-between p-2 md:p-4">
        <SearchBar />
        <Select />
      </div>
      <div className="flex flex-wrap justify-between gap-4 p-2 md:p-4">
        {/** @ts-expect-error Server component */}
        <Countries countries={countries} />
      </div>
    </main>
  );
}

PS:你可能要想办法通过queryParams以安全的方式发送密码。我不知道你会怎么做。

相关问题