【发布时间】:2020-07-21 12:41:06
【问题描述】:
我正在使用 Next Js (React SSR) 制作服务器端渲染应用程序。
Index.js(只需在索引中调用另一个组件Layout)
import Layout from "./layout";
import React from "react";
class Home extends React.Component {
render() {
return (
<div>
<Layout />
</div>
);
}
}
export default Home;
Layout.js
import React from "react";
import Product from "./product";
class Layout extends React.Component {
static async getInitialProps() {
const res = await fetch("https://api.github.com/repos/developit/preact");
console.log(res);
const json = await res.json();
return { stars: json.stargazers_count };
}
componentDidMount() {
if (localStorage.getItem("userLoggedIn")) {
//Get products details for logged in user api
//For now let us consider the same api
// const res = fetch("https://api.github.com/repos/developit/preact");
// const json = res.json(); // better use it inside try .. catch
// return { stars: json.stargazers_count };
} else {
// Get product details for guest user api
//For now let us consider the same api
// const res = fetch("https://api.github.com/repos/developit/preact");
// const json = res.json();
// return { stars: json.stargazers_count };
}
}
render() {
return (
<div>
This is layout page
<Product stars={this.props.stars} />
</div>
);
}
}
export default Layout;
完整的简单应用示例在这里:https://codesandbox.io/s/nextjs-getinitialprops-748d5
我的问题是,我正在尝试将道具从 layout 页面传递到 product 页面,并且道具是从 getInitialProps (SSR) 接收的。但是您可以在提供的示例中看到,道具没有t 工作,它仍然为this.props.stars 提供 undefined 。
如果我将此代码移动到 componentDidMount 并使用 setState 并将状态作为道具传递将起作用,但不会在视图页面源中显示从 api 获取的数据。
注意:请不要将此逻辑移动到它工作的 index.js 文件中,但在我的实际应用程序中它是动态路由页面,我将根据获取的查询参数获取 api页面。
如果您进入此链接https://748d5.sse.codesandbox.io/ 并单击ctrl + u,那么您会看到我还需要从 api 获取的动态内容的来源。
为了实现这个动态内容(在这个例子中是星号)只在视图源中显示,我正在做所有这些都是为了 SEO 目的。
【问题讨论】:
标签: javascript reactjs next.js server-side-rendering