【问题标题】:Is it possible to get a search term parameter into getServerSideProps()?是否可以在 getServerSideProps() 中获取搜索词参数?
【发布时间】:2021-09-12 09:18:32
【问题描述】:

我正在创建一个页面,我可以在其中概览我的所有笔记/摘要。

笔记的页面是转换成动态文件中使用的 HTML 的 Markdown 文件(这有效)。

在笔记页面(列出所有笔记)上,我想实现一个搜索功能:
我需要找到一种方法将我的搜索输入值输入getServerSideProps()。这样它就可以过滤掉笔记,只显示你搜索的那些。

注意事项:

  • 当我在注释页面中更改 getServerSideProps() 中的字符串 'searchTerm' 时,搜索功能会起作用。
const searchTerm = "" ;
  • 我无法将getAllNotes() 移到getServerSideProps() 之外,因为无法在客户端访问数据文件的导入。
const allNotes = getAllNotes();
  • 我知道,搜索栏需要居中。

备注页代码:

import Head from 'next/head';
import Link from 'next/link';
import Footer from '../../components/Footer.js';
import Navigation from '../../components/Navigation';

import { Rating } from '@material-ui/core';
import Chip from '../../components/Chip.js';

import noteStyle from '../../styles/Notes.module.css';
import styles from '../../styles/Home.module.css';


import { getAllNotes } from '../../lib/data';
import Search from '../../components/Search';
export default function Notes({ notes }) {
  return (
    <div id="top" className={styles.container}>
      <Head></Head>

      <main className={styles.main}>
        <section>
          <Navigation />
        </section>
        <section className={noteStyle.noteSection}>
          <h1>Notes & Summaries</h1>
          
          <Search />

          <div className={noteStyle.notes}>
            {notes.map((note) => (
              <Link key={note.slug} href={`/note/${note.slug}`}>
                <a key={note.slug} className={noteStyle.noteCard}>
                  <h2 key="title">{note.title}</h2>
                  <h3 key="author">{note.author}</h3>
                  <p key="abstract">
                    {note.abstract}
                  </p>
                  <div className={noteStyle.aboutNote}>
                    <Rating key="rating" className={noteStyle.rating} name="half-rating-read" defaultValue={note.rating} precision={0.5} readOnly />
                    <Chip key="label" className={noteStyle.noteChip} bgColor={note.labelColors[0]} text={note.labelText[0]} icon={note.labelIcons[0]} />
                  </div>
                </a>
              </Link>
            ))}

          </div>
        </section>
      </main>
      <Footer />
    </div>
  )
}

export async function getServerSideProps() {
  const allNotes = getAllNotes();
  const searchTerm = "";

  //Searches in title, author & abstract data field for a match with the query
  const searchNotes = allNotes.filter((note) => {
    return note.data.title.toLowerCase().includes(searchTerm.toLowerCase()) || note.data.author.toLowerCase().includes(searchTerm.toLowerCase()) || note.data.abstract.toLowerCase().includes(searchTerm.toLowerCase())
  });

  

  return {
    props: {
      //Here data serialising (dates, urls, ...),
      notes: searchNotes.map(({ data, content, slug }) => ({
        ...data,
        content,
        slug,
      })),

    },
  };
};

搜索组件的代码:

import { useState } from 'react';

export default function Search() {
    const [input, setInput] = useState('');

    const search = (e) => {
        setInput(e.target.value);
        console.log("You searched", input);
    }

    return (
        <div className={style.search}>
                <SearchIcon className={style.search__inputIcon}/>
                <input type="text" placeholder="Search for a note..." value={input} onChange={search} />
        </div>
    )
}

getAllNotes的代码(这个函数将所有的markdown文件转换成HTML):

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

const contentDirectory = path.join(process.cwd(), '_content');

export function getAllNotes() {
  const allNotes = fs.readdirSync(contentDirectory);

  return allNotes.map(fileName => {
    const slug = fileName.replace('.md', '');
    const fileContents = fs.readFileSync(
      path.join(contentDirectory, fileName),
      'utf-8'
    )
    const {content, data} = matter(fileContents);
    return {
      data,
      content,
      slug,
    };  
  })
}

我在构建页面时使用的研究:

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    要使客户端代码中的值可用于getServerSideProps,您可以使用router.push 在URL 上传递查询参数。

    // In your `Notes` or `Search` component
    
    router.push('/notes?searchTerm=hello');
    

    然后您可以从getServerSideProps 中的查询参数访问该值。

    export async function getServerSideProps(context) {
        const searchTerm = context.query.searchTerm ?? "" // `context.query.searchTerm` would contain "hello"
    
        // ...
    }
    

    【讨论】:

    • 感谢您的回复,我尝试了这个示例并且它有效。但仅在我的本地主机上。当我尝试托管这个时,它给出了 500:内部服务器错误。这是URL。在控制台中,您还可以看到它为 GET /notes 提供了 500 ...知道为什么会这样吗?
    • 您能否在本地运行生产构建时复制该问题 (next build &amp;&amp; next start)?另外,你能显示你当前的getServerSideProps 代码吗?它很可能与那里的某些东西有关(可能在getAllNotes 代码中)。
    • 我尝试在本地构建和启动,它按预期工作。我就这个新问题here 提出了一个新问题。所有相关代码都应该在那里。 :)
    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多