0

我在使用 Next.JS 并为我的页面获取初始道具时遇到问题。我正在做一个有几个(7-8)页的应用程序。在左侧菜单中,单击图标后,路由器会将用户推送到正确的页面。然后,如果用户登录,页面和子组件就会加载。一切正常,因为我试图用加载组件来覆盖加载时间,如下所示:

  render() {

if (this.props.data !== undefined) {
  return (<Provider store={store}><Main info={this.props.data}  path={this.props.url.pathname} user={this.props.user} token={this.props.token} /></Provider>)
} else {
  return (<Loading />)
}}

设计目标是在获取数据时启动加载组件。不是之后。我试图用 React 生命周期钩子来做,但似乎`

静态异步 getInitialProps({req})

先于一切。查看整个代码

export default class Component extends React.Component {

static async getInitialProps({req}) {
const authProps = await getAuthProps(req, 
'url')
return authProps;
  }

  componentDidMount() {
if (this.props.data === undefined) {
  Router.push('/login')
}
  }

  render() {

if (this.props.data !== undefined) {
  return (<Provider store={store}><Main info={this.props.data}  path={this.props.url.pathname} user={this.props.user} token={this.props.token} /></Provider>)
} else {
  return (<Loading />)
}}}
4

1 回答 1

0

getInitalProps页面组件被渲染时被调用。您不应该在任何其他组件中使用它,因为它不起作用。这不是 React 生命周期的一部分,而是 Next 的实现。我相信您想要做的只是获取数据并测量其加载时间。如果是这样,那么使用 componentDidMount 可能就足够了。

于 2017-10-09T14:11:36.700 回答