【问题标题】:Next.js data loading IssueNext.js 数据加载问题
【发布时间】:2018-03-19 20:29:32
【问题描述】:

我在使用 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 />)
}}}

【问题讨论】:

    标签: reactjs components fetch next.js react-lifecycle


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多