reactjs - 我可以将 getInitialProps 代码移动到 componentDidMount 吗?
问题描述
我想将静态 getInitialProps 中的代码移动到 componentDidMount。但是,getInitialProps 中有两个参数(组件,ctx),我应该全部使用它们。我只想知道我是否可以移动代码。谢谢!
不知道..
// Current
class extends App {
public static async getInitialProps({Component, ctx}) {
// Do Something with two parameters
}
.
.
.
}
// What I want to do
class extends App {
public componentDidMount() {
// Do the same thing
}
.
.
.
}
解决方案
getInitialProps
在服务器端和客户端都可以使用,而componentDidMount
仅适用于客户端。因此,您不能在内部使用它componentDidMount
。
如果您想使用getInitialProps
在 componentDidMount 中获取的数据,您可以从中返回数据getInitialProps
并将其用作prop
.
class extends App{
static async getInitialProps({ Component, ctx }) {
//do some data fetching
return { data };
}
constructor() {
super();
this.state = {};
}
componentDidMount() {
console.log(this.props.data)
}
}
推荐阅读
- docker-compose - 如何解决 traefik 中的 404 eero。子域显示 404 但暴露端口工作正常
- google-colaboratory - 摆脱出现在合作中的狗
- javascript - Dojo javascript 工具包,我在一个模块中定义了两个函数。我怎么能从另一个打电话给一个
- signalr - 信号连接到集线器但不能调用方法
- python - 将函数动态插入 Python 类
- flutter - Flutter Mobx - 在 PageView 的页面之间传递存储状态
- haskell - 如何从 Haskell Stack 构建中编译可执行文件?
- mysql - Sequelize Op.or order by first by exact match first
- javascript - 如何重置jquery动态选择选项?
- python - 如何在 os.utime 中使用 windows 路径?