我正在使用 Next Js (React SSR) 制作服务器端渲染应用程序。
Index.js(只需在index中调用另一个组件Layout即可)
import Layout from "./layout";
import React from "react";
class Home extends React.Component {
render() {
return (
<div>
<Layout />
</div>
);
}
}
export default Home;
布局.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 https://codesandbox.io/s/nextjs-getinitialprops-748d5
我的问题是,我试图将道具传递给product
页面来自layout
页面和道具来自getInitialProps
(SSR)..但是您可以在提供的示例中看到,道具不起作用,但它仍然给出不明确的 for this.props.stars
.
如果我将这段代码移入componentDidMount
并使用setState
并将状态作为 props 传递可以工作,但不会在视图页面源中显示从 api 获取的数据。
Note:请不要将此逻辑移动到它起作用的 index.js 文件中,但在我的实际应用程序中,它是动态路由页面,我将根据在该页面上获取的查询参数来获取 api。
如果您进入此链接https://748d5.sse.codesandbox.io/ https://748d5.sse.codesandbox.io/然后单击ctrl + u
然后你会看到我还需要从 api 获取动态内容的源。
为了实现这个动态内容(在这个例子中星星计数)仅在视图源中显示,我正在做所有这些都是为了 SEO 目的。