我有这样的代码来检查,如果用户进行身份验证Next.js服务器端的路由
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)
}
它的伟大工程,但是当我尝试将用户重定向我得到这个错误:
找不到路由器实例。你应该只在你的应用的客户端使用“next/router”。
,如果我尝试使用this.props.url.replaceTo('/login')
我得到这样的警告
警告: 'url.replaceTo()' 已过时。使用“下一个/路由器”API。
所以这是让我疯狂,我想知道是否有一种方法来实现这种重定向或另一种方式来控制身份验证在这种情况下,只是一个线索将是伟大的。