简体   繁体   English

如何在 Next.js 中重新查询数据

[英]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 并将结果存储在状态中,但存储在服务器端。

  • How can I handle this so it renders on the server and not the client like getInitialProps does?我该如何处理它以便它在服务器上呈现而不是像getInitialProps那样呈现在客户端上?
  • Is there something special I need to do in my function to make it run on the server?我需要在我的函数中做一些特别的事情来让它在服务器上运行吗?
  • Should I just recall getInitialProps and pass in the search term?我应该回忆一下getInitialProps并传入搜索词吗?
  • What's the best way to get the search query to render on the server and not the client?让搜索查询呈现在服务器上而不是客户端上的最佳方法是什么?

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.

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