好的,这是我关于 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.
注意:我使用的是快递
答案 0 :(得分:0)
我刚刚解决了,解决方法是在找不到数据时为每个变量声明一个空数组:
serverProducers: producers?.data || [],
serverVideos: videos?.data || [],
serverProfiles: profiles?.data || []
仍然不确定为什么我需要再次创建第二个 || []
,但这是唯一有效的方法。