Arn*_*las 5 javascript authentication reactjs nextjs
我有此代码来检查用户是否已通过身份验证
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)
}
Run Code Online (Sandbox Code Playgroud)
效果很好,但是当我尝试重定向用户时出现此错误:
找不到路由器实例。您只应在应用程序客户端内部使用“下一个/路由器”。
如果我尝试使用,则会this.props.url.replaceTo('/login')收到此警告
警告:不建议使用“ url.replaceTo()”。使用“下一个/路由器” API。
所以这让我发疯,我想知道是否有一种方法可以实现这种重定向,或者在这种情况下可能还有另一种控制身份验证的方法,这将是一个很好的线索。
| 归档时间: |
|
| 查看次数: |
4532 次 |
| 最近记录: |