【发布时间】:2020-07-27 18:02:29
【问题描述】:
我在 NextJS 应用程序中遇到问题。
在_app.js 文件中,我实例化了一个Context(它又实例化了一个State)
在我的页面ContextTest 我声明了一个getServerSideProps()。
这会从 API 返回一些数据,这些数据会传递给 _app.js 并保存到 Context's state。
到目前为止,我有我需要的数据。
然后它转到目标页面组件,该组件读取上下文的状态并设置一个变量。 组件成功输出我的变量,形式为
let userName = userState.username ? userState.username : 'Guest'
当页面加载时,我检查请求中的 HTML,确实我有 userState.username 值。
但是浏览器中显示的 HTML 有Guest。
有两点需要注意:
1) 服务器端按预期呈现
2)该应用程序在该页面的客户端中再次执行(那么为什么我要渲染应用程序服务器端呢?)。结果是这个页面没有getServerSideProps() 的结果,所以我的状态是空的,我在控制台中收到警告。
3) 浏览器中显示的 HTML 是客户端执行 React 应用程序的结果。 (为什么?)
__app.js
import React, {useContext} from "react";
import {UserContext} from "../lib/Context/UserContext"
export default function RankerApp({Component, pageProps}) {
const [userState, setUserState] = useContext(UserContext)();
const [listState, setListState] = useContext(ListContext)();
if (pageProps.serverContext && pageProps.serverContext.user) {
setUserState({...userState, ...pageProps.serverContext.user})
}
delete pageProps['serverContext'];
return (
<ListContext.Provider value={[listState, setListState]}>
<UserContext.Provider value={[userState, setUserState]}>
<Component {...pageProps} />
</UserContext.Provider>
</ListContext.Provider>
);
}
pages/contextTest.js
import React, {useContext} from 'react';
import {UserContext} from "../lib/Context/UserContext";
import Link from "next/link";
import UserContextSeeder from "../lib/User/UserContextSeeder";
export default function ContextPage1(props) {
let [userState, setUserState] = useContext(UserContext);
const currentLoggedInUserData = userState.loggedInUserId ? userState.users[userState.loggedInUserId] : null;
const currentLoggedInUserName = currentLoggedInUserData ? currentLoggedInUserData.userName : 'Guest';
return (
<div>
<h1>Page 1</h1>
<Link href="contextTest2">
<a>Page 2</a>
</Link>
<h1>Current Logged In User: {currentLoggedInUserName}</h1>
</div>
);
}
export async function getServerSideProps(context) {
let userContext = {};
// await UserContextSeeder(context).then(context => {userContext = context}); commented for simplicty
userContext = {loggedInUserId: 222, users: {222: {userName: "Jorge"}}; // suppose this is the result
return {
props: {
serverContext: {
user: {...userContext}
}
},
}
}
【问题讨论】:
标签: javascript reactjs next.js server-side-rendering