React/Next呈现问题,客户端和服务器显示不同的数据



我在网页上实现了一个部分,在上面显示图像背景和城市名称

生成图像背景和城市数据的数据文件是对象的标准阵列。棘手的部分是,必须动态加载每个对象的图像路径才能使用Webpack,所以形状看起来像这样:

// Data
import Copenhagen from "../../public/case-studies/PFB_CR_Case_Copenhagen.jpg";
import NYC from "../../public/case-studies/PFB_CR_Case_NYC.jpg";
import SLO from "../../public/case-studies/PFB_CR_Case_SanLuisObispo.jpg";
import Sevilla from "../../public/case-studies/PFB_CR_Case_Sevilla.jpg";
import DC from "../../public/case-studies/PFB_CR_Case_WashingtonDC.jpg";
export const hpCaseStudies = [
{
city: "Copenhagen",
image: Copenhagen
},
{
city: "New York City",
image: NYC
},
{
city: "San Luis Obispo",
image: SLO
},
{
city: "Sevilla",
image: Sevilla
},
{
city: "Washington",
image: DC
}
];

在下一页中,我将这样实现:

// Component
const Index = () => {
// Gets a random case study index
const csi = randomID(hpCaseStudies.length - 1);
// Shuffles array, sets it into state
useEffect(() => {
arrayShuffle(hpCaseStudies);
}, []);
const [caseStudies, setCaseStudies] = useState(hpCaseStudies);
// in render, we should see a random city and background image each pageview
// but the client and server show different things, resulting in an error
return (
<HeaderImage
source={caseStudies[csi].image}
tagContent="Case Study"
tagStatus={true}
>
<SecondaryHeading>{caseStudies[csi].city}</SecondaryHeading>
</HeaderImage>
);
};
export default Index;

有时,当cityimage相同但它们经常不同步时,它会起作用。我想我在React钩子生命周期的某个地方遇到了麻烦,但我被难住了。

错误(参考caseStudies.city值不匹配(:

Warning: Text content did not match. Server: "New York City" Client: "Sevilla"
at h2
at styled.h2 (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:28:19599)
at section
at styled.section (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:28:19599)
at HeaderImage (webpack-internal:///./components/global/header-image.js:74:23)
at Index (webpack-internal:///./pages/index.js:42:58)
at App (webpack-internal:///./node_modules/next/dist/pages/_app.js:76:5)
at ErrorBoundary (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ErrorBoundary.js:23:47)
at ReactDevOverlay (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js:73:23)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:156:5)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:645:24)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:778:24)

沙盒:https://codesandbox.io/s/next-client-server-mismatch-7wzr4

在打开沙箱控制台的情况下重新加载沙箱浏览器,您会看到错误。不过,有时客户端和服务器会匹配并正确显示。

const csi = randomID(hpCaseStudies.length - 1);

这就是问题所在。此代码运行两次:一次在服务器上,一次在客户端上。很明显,在这两次跑步的大部分时间里,它都会不匹配。

您需要为两个渲染生成相同的ID。如果想保持服务器端渲染,那么可以在getServerSideProps中进行,例如:

export async function getServerSideProps(context) {
return {
props: {
// will be passed to the page component as props
randomId: randomID(hpCaseStudies.length - 1)
}, 
}
}

或者其他一些服务器端数据提取方法

最新更新