简体   繁体   English

我希望在 Next.JS 中创建 2 个页面,其中 2 个页面之间有分页和 args

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

What I want: Create 2 page in Next.JS in React.JS that can do the following:我想要什么:在 React.JS 中的 Next.JS 中创建 2 个页面,可以执行以下操作:

  • User lands in the page 1 (/home) where there is a search bar用户登陆有搜索栏的第 1 页(/home)
  • User type in the page 1 type what he wants in the search bar and validate the form用户在页面中输入 1 在搜索栏中输入他想要的内容并验证表单
  • User is redirected to the page 2 (/search/:parameter) with the query string in the URL parameter...使用 URL 参数中的查询字符串将用户重定向到第 2 页(/search/:parameter)...
  • Make an HTTP request into the page 2 with the arg passed向第 2 页发出 HTTP 请求并传递 arg
  • Show to the user the result of the http request向用户显示 http 请求的结果

What I tried to do and I didn't successfully to do that我试图做的事情,但我没有成功地做到这一点

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>
    )
  }
}

So, I'm stuck I'm blocked I already did not succeed to make my submit form function working.所以,我被卡住了,我被阻止了我已经没有成功让我的提交表单 function 工作。 How to do it?怎么做?

First you have to get the value of the input on submit and programatically changing the current route :首先,您必须在提交时获取输入值并以编程方式更改当前路线

You can get the value by making a ref to the <input /> element:您可以通过对<input />元素进行引用来获取值:

Your first page should look like this /pages/index.js您的第一页应如下所示/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>
  );
}

This will get you to /search/[the value you submitted] .这将使您进入/search/[the value you submitted]

In order to create that dynamic page you should use the Dynamic API Routes .为了创建该动态页面,您应该使用Dynamic API Routes

Just create a file named /pages/[paramPassed].js只需创建一个名为/pages/[paramPassed].js的文件

I made an example with the jsonplaceholder api:我用 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
  };
}

The getServerSideProps allows you to set default params to your page component before rendering it. getServerSideProps允许您在渲染页面组件之前为其设置默认参数。
You can use the fetch API or SWR inside your React components for remote data fetching;您可以在 React 组件中使用 fetch API 或 SWR 进行远程数据获取; or use Next.js' data fetching methods for initial data population.或使用 Next.js 的数据获取方法进行初始数据填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM