reactjs - 为什么nextjs中没有显示数据?
问题描述
我正在制作一个非常简单的 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;
布局.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;
因此,根据上面给出的代码,我已经调用了layout
页面内的index.js
页面(在我的真实应用程序中,我只需要像这样调用,所以在索引内调用布局没有变化)..
但是当我在布局console.log()
中的函数中创建一个时Layout.getInitialProps
,它不会打印任何东西,因此没有获取 api 数据..
为什么我不能在layout.js
作为孩子调用的时候从里面获取数据index.js
?
还为我提供正确的更新解决方案来实现这一点。我真的搜索了很多问题,但没有一个解决我的问题,我无法清楚地理解这些解决方案,所以请帮助我上面给出的例子。
解决方案
那是因为 getInitialProps
只能添加到页面导出的默认组件中,将其添加到任何其他组件都不起作用。
您应该使用componentDidMount()
oruseEffect
代替,或者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;
布局.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;
编辑:
带有类组件的示例
奖励:如果您想为应用程序的所有页面添加布局,这不是最好的方法,相反您应该查看自定义 _app.js,示例
推荐阅读
- java - Docker 容器无法使用 Java 12 运行 jacoco 代理
- javascript - 如何通过变量将数据插入 MySQL 数据库?
- r - Plotly 图层控制:如何在形状前面添加文本
- swift - 如何在 swift 中从 webView 打开外部链接?
- python - 有没有办法将变量传递给 html 表单操作属性?
- swift - 同一个 UITableViewCell 中的两个标签约束
- encryption - 加密程序
- node.js - 如何使用不同的身份合并 Git 分支?
- go - Golang 解释 gdb SIGILL,非法指令
- cloudflare - 在长时间运行的脚本上防止 Cloudflare 524