簡體   English   中英

我希望在 Next.JS 中創建 2 個頁面,其中 2 個頁面之間有分頁和 args

[英]I wish create 2 pages in Next.JS with pagination and args between the 2

我想要什么:在 React.JS 中的 Next.JS 中創建 2 個頁面,可以執行以下操作:

  • 用戶登陸有搜索欄的第 1 頁(/home)
  • 用戶在頁面中輸入 1 在搜索欄中輸入他想要的內容並驗證表單
  • 使用 URL 參數中的查詢字符串將用戶重定向到第 2 頁(/search/:parameter)...
  • 向第 2 頁發出 HTTP 請求並傳遞 arg
  • 向用戶顯示 http 請求的結果

我試圖做的事情,但我沒有成功地做到這一點

import Head from 'next/head'
import React, { Component } from 'react'
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import Link from 'next/link'

function submitForm() {
  if(process.browser) {
    alert(document.getElementById('subvalue').value)
  }
}

export default class Home extends React.Component {

  render() {
    return (
      <div className="container">
        <Head>
          <title>Reddit Feed App</title>
          <link rel="icon" href="/favicon.ico" />
        </Head>

        <main>
          <form action="#" onSubmit={this.handleSubmit}>
            <label>Search for any subreddit :</label>
            <input type="text" id="subvalue"/>
            <span onClick={submitForm()} >Submit</span>
          </form>
        </main>
         ...
      </div>
    )
  }
}

所以,我被卡住了,我被阻止了我已經沒有成功讓我的提交表單 function 工作。 怎么做?

首先,您必須在提交時獲取輸入值並以編程方式更改當前路線

您可以通過對<input />元素進行引用來獲取值:

您的第一頁應如下所示/pages/index.js

import { useRouter } from "next/router";
import { useRef } from "react";

export default function IndexPage() {
  const router = useRouter();
  const inputRef = useRef(null);
  const onSubmit = (e) => {
    e.preventDefault();
    // some validations here
    router.push(`search/${inputRef.current.value}`);
  };
  return (
    <form onSubmit={onSubmit}>
      <input name="second_page" type="number" ref={inputRef} />
      <button type="submit">submit</button>
    </form>
  );
}

這將使您進入/search/[the value you submitted]

為了創建該動態頁面,您應該使用Dynamic API Routes

只需創建一個名為/pages/[paramPassed].js的文件

我用 jsonplaceholder api 做了一個例子:

export default function Search({ res }) {
  return (
    <div>
      Here's the result :
      <pre>
        <code>{JSON.stringify(res)}</code>
      </pre>
    </div>
  );
}

export async function getServerSideProps({ params }) {
  const { paramPassed } = params;

  const req = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${paramPassed}`
  );
  const res = await req.json();

  return {
    props: { res } // will be passed to the page component as props
  };
}

getServerSideProps允許您在渲染頁面組件之前為其設置默認參數。
您可以在 React 組件中使用 fetch API 或 SWR 進行遠程數據獲取; 或使用 Next.js 的數據獲取方法進行初始數據填充。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM