我有這樣的代碼來檢查,如果用戶進行身份驗證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。
所以這是讓我瘋狂,我想知道是否有一種方法來實現這種重定向或另一種方式來控制身份驗證在這種情況下,只是一個線索將是偉大的。