Next.js服务器端路由

JavaScript React.js

村村

2020-03-23

我有此代码来检查用户是否已通过身份验证

const withAuth = AuthComponent => {
  class Authenticated extends Component {
    static async getInitialProps (ctx) {
      let componentProps
      if (AuthComponent.getInitialProps) {
        componentProps = await AuthComponent.getInitialProps(ctx)
      }
      return {
        ...componentProps
      }
    }
    componentDidMount () {
      this.props.dispatch(loggedIn())
    }
    renderProtectedPages (componentProps) {
      const { pathname } = this.props.url
      if (!this.props.isAuthenticated) {
        if (PROTECTED_URLS.indexOf(pathname) !== -1) {
          // this.props.url.replaceTo('/login')
          Router.replace('/login')                   // error
        }
      }
      return <AuthComponent {...componentProps} />
    }
    render () {
      const { checkingAuthState, ...componentProps } = this.props
      return (
        <div>
          {checkingAuthState ? (
            <div>
              <h2>Loading...</h2>
            </div>
          ) : (
            this.renderProtectedPages(componentProps)
          )}
        </div>
      )
    }
  }
  return connect(state => {
    const { checkingAuthState, isAuthenticated } = state.data.auth
    return {
      checkingAuthState,
      isAuthenticated
    }
  })(Authenticated)
}

效果很好,但尝试重定向用户时出现此错误:

找不到路由器实例。您只应在应用程序客户端内部使用“下一个/路由器”。

如果我尝试使用this.props.url.replaceTo('/login')此警告

警告:不建议使用“ url.replaceTo()”。使用“下一个/路由器” API。

所以这让我发疯,我想知道是否有一种方法可以实现这种重定向,或者在这种情况下可能还有另一种控制身份验证的方法,这将是一个很好的线索。

第3034篇《Next.js服务器端路由》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
蛋蛋古一 2020.03.23

我也想在服务器端找到解决方案。但是我通过写“ document.location = xxx”在客户端上修复了它

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android