我正在制作一个非常非常简单的 nextjs 应用程序,我试图从 api 获取数据。
我的要求是我应该在 layout.js
文件中显示数据,并且这个 layout.js
文件是 index.js
中的子文件文件。
index.js:
import Layout from "./layout";
import React from "react";
class Home extends React.Component {
render() {
return (
<div>
<Layout />
<h4> Main content will be displayed here !! </h4>
</div>
);
}
}
export default Home;
layout.js:
import React from "react";
import fetch from "isomorphic-unfetch";
function Layout(props) {
return (
<div>
<p>Preact has {props.stars} ⭐</p>
<p> Why I couldn't get the above "props.star" ? </p>
</div>
);
}
Layout.getInitialProps = async () => {
console.log("comes into layout getinitial props");
const res = await fetch("https://api.github.com/repos/developit/preact");
const json = await res.json(); // better use it inside try .. catch
return { stars: json.stargazers_count };
};
export default Layout;
因此,根据上面给出的代码,我在 index.js
页面中调用了 layout
页面(在我的实际应用程序中,我只需要像这样调用,所以不需要索引内调用布局的变化)..
但是当我在布局中的函数 Layout.getInitialProps
中创建 console.log()
时,它不会打印任何内容,因此不会获取 api 数据。 .
Complete working demo here with code
为什么我在从 index.js
作为子级调用时无法获取 layout.js
内的数据?
还为我提供正确的更新解决方案来实现这一目标。我确实搜索了很多问题,但没有一个解决我的问题,而且我无法清楚地理解这些解决方案,所以请帮助我解决上面给出的示例。
最佳答案
因为 getInitialProps
只能添加到页面导出的默认组件中,因此将其添加到任何其他组件中都不起作用。
您应该使用 componentDidMount()
或 useEffect
来代替,或者将 getInitialProps
移动到索引中,然后将结果传递给组件。类似(未测试):
index.js:
import Layout from "./layout";
import React from "react";
class Home extends React.Component {
render() {
return (
<div>
<Layout />
<h4> Main content will be displayed here !! </h4>
</div>
);
}
}
export default Home;
layout.js
import React from "react";
import fetch from "isomorphic-unfetch";
class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
stars: false
};
}
async componentDidMount() {
console.log("comes into layout getinitial props");
const res = await fetch("https://api.github.com/repos/developit/preact");
const json = await res.json(); // better use it inside try .. catch
this.setState({ stars: json.stargazers_count });
}
render() {
const { stars } = this.state;
return (
<div>
<p>Preact has {stars} ⭐</p>
<p> Why I couldn't get the above "props.star" ? </p>
</div>
);
}
}
export default Layout;
编辑:
Example带有类组件
奖励:如果您想为应用程序的所有页面添加布局,这不是最好的方法,您应该看看 custom _app.js , example
关于reactjs - 为什么nextjs中数据不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59644618/