0

好的,这是我关于 NextJS 的第三篇文章。

我目前正在制作一个搜索页面,该页面需要根据 URL 中找到的关键字从 3 个端点获取数据;如果未找到数据,则在正确的调用中显示一条消息。

即使在 1-2 个端点中找到数据,当前行为也会引发错误:

import { useEffect, useState, useContext } from 'react';
import { withRouter } from 'next/router';
// ACTIONS
import { getProducersFromServer } from '@/actions/producer';
import { getVideosFromServer } from '@/actions/video';
import { getProfilesFromServer } from '@/actions/profile';
// HELPERS
import Layout from '@/layout/Layout';
import { PUBLIC_URL } from '../../config';
import NothingFoundAlert from '@/layout/NothingFoundAlert';
import AuthContext from '@/routing/authContext';
// REACTBOOTSTRAP
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
// NESTED COMPONENTS
import SearchMenu from './SearchMenu';
import SingleProducer from '../producers/singleProducer';
import SingleVideo from '../videos/singleVideo';
import SingleProfile from '../profiles/singleProfile';

export const getServerSideProps = async (context) => {
  const keyword = context.query.keyword;
  const params = `?keyword=${keyword}&page=${context.query.page}&limit=${context.query.limit}&sort=${context.query.sort}&status=${context.query.status}`;
  const producers = (await getProducersFromServer(params)()) || [];
  const videos = (await getVideosFromServer(params)()) || [];
  const params2 = `?keyword=${keyword}&page=${context.query.page}&limit=${context.query.limit}&sort=${context.query.sort}&isEmailConfirmed=true`;
  const profiles = (await getProfilesFromServer(params2)()) || [];

  return {
    props: {
      params: params,
      params2: params2,
      keyword: keyword,
      serverProducers: producers?.data,
      serverVideos: videos?.data,
      serverProfiles: profiles?.data
    }
  };
};

const All = ({
  params,
  params2,
  keyword,
  serverProducers,
  serverVideos,
  serverProfiles,
  router
}) => {
  const [searchProducerResults, setSearchProducerResults] = useState([]);
  const [searchVideoResults, setSearchVideoResults] = useState([]);
  const [searchProfileResults, setSearchProfileResults] = useState([]);

  useEffect(() => {
    setSearchProducerResults(serverProducers);
    setSearchVideoResults(serverVideos);
    setSearchProfileResults(serverProfiles);
  }, [params]);
  const { auth } = useContext(AuthContext);
  return (
    <Layout
      title={`Search Results of ${keyword}`}
      description={`Search results`}
      author={`Kevin Fonseca`}
      sectionClass={`mb-3`}
      containerClass={`container`}
      canonical={`${PUBLIC_URL}`}
      url={`search${params}`}
    >
      <SearchMenu params={params} params2={params2} />
      <div
        className={
          auth?.user?.data?.settings.theme.themeContainer
            ? auth?.user?.data.settings.theme.themeContainer
            : `container`
        }
      >
        <Row>
          <Col xl={`12`} lg={`12`}>
            {searchProducerResults?.length > 0 ? (
              <>
                <h4 className={`my-2 mb-3`}>
                  Producers ({totalProducerResults})
                </h4>
                {searchProducerResults.map((producer, index) => (
                  <SingleProducer key={producer._id} producer={producer} />
                ))}
              </>
            ) : (
              <NothingFoundAlert />
            )}
            {searchVideoResults?.length > 0 ? (
              <>
                <hr />
                <h4 className={`my-2 mb-3`}>Videos ({totalVideoResults})</h4>
                <div className={`recommendedVideos_videos`}>
                  {searchVideoResults.map((video, index) => (
                    <SingleVideo key={video._id} video={video} />
                  ))}
                </div>
              </>
            ) : (
              <NothingFoundAlert />
            )}
            {searchProfileResults?.length > 0 ? (
              <>
                <hr />
                <h4 className={`my-2 mb-3`}>
                  Profiles ({totalProfileResults})
                </h4>
                <div className={`profiles-container`}>
                  {searchProfileResults
                    .filter((profile) => profile._id !== auth?.user.data._id)
                    .map((profile, index) => (
                      <SingleProfile
                        key={profile._id}
                        profile={profile}
                        auth={auth}
                      />
                    ))}
                </div>
              </>
            ) : (
              <NothingFoundAlert />
            )}
          </Col>
        </Row>
      </div>
    </Layout>
  );
};

export default withRouter(All);

在上面的代码中,我试图NothingFoundAlert在每个变量中显示组件,但它当前会引发以下错误:

Error: Error serializing `.serverProducers` returned from `getServerSideProps` in "/search".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

注意:我正在使用快递

4

1 回答 1

0

I just solved it, the solution was to declare an empty array for each variable when data was not found:

serverProducers: producers?.data || [],
serverVideos: videos?.data || [],
serverProfiles: profiles?.data || []

Still unsure why I need to create a second || [] again but this is the only way it works.

于 2021-05-05T04:11:52.557 回答