[英]How to requery data in Next.js
I just started learning Next.js and I'm having some issues with querying data.我刚开始学习 Next.js,但在查询数据时遇到了一些问题。
I understand that getInitialProps
is used to query an API and get the data, and it's rendering on the server.我知道
getInitialProps
用于查询 API 并获取数据,并在服务器上呈现。
I want a search box where the user search, and as they type, it repeatedly queries the API in a function and stores the results in state, but server-side.我想要一个用户搜索的搜索框,当他们输入时,它会重复查询函数中的 API 并将结果存储在状态中,但存储在服务器端。
getInitialProps
does?getInitialProps
那样呈现在客户端上?getInitialProps
and pass in the search term?getInitialProps
并传入搜索词吗?There is no way to make this dynamic (as user types in) search on the server.无法在服务器上进行这种动态(当用户输入时)搜索。 This needs to be handled on UI as per docs
这需要根据文档在 UI 上处理
For the initial page load, getInitialProps will execute on the server only.
对于初始页面加载,getInitialProps 将仅在服务器上执行。 getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.
getInitialProps 只会在通过 Link 组件导航到不同路由或使用路由 API 时在客户端上执行。
The only search that will be prerendered on the server is the one that reloads that page.将在服务器上预呈现的唯一搜索是重新加载该页面的搜索。
Example例子
<form action="/search-enpoint">
<input name="search" type="text" placeholder="Search" />
<button>Find</button>
</form>
This form will be submitted to /search-enpoint?search=qwe
that you can catch in custom server此表单将提交到
/search-enpoint?search=qwe
您可以在自定义服务器中捕获
// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === '/search-enpoint') {
app.render(req, res, '/index', query);
} else {
handle(req, res, parsedUrl);
}
}).listen(3000, err => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
But again this search is not dynamic.但同样,这种搜索不是动态的。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.