[英]I wish create 2 pages in Next.JS with pagination and args between the 2
我想要什么:在 React.JS 中的 Next.JS 中創建 2 個頁面,可以執行以下操作:
我試圖做的事情,但我沒有成功地做到這一點
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.