我正在为React应用设置路线。进入我的主页时,我想从Auth0记录一些数据。为此,我只是简单地使用onEnter属性,但似乎它不起作用。
import React from 'react'
import {Route, IndexRedirect} from 'react-router'
import AuthService from 'utils/AuthService'
import Container from './Container'
import Home from './Home/Home'
import Login from './Login/Login'
[...]
const requireAuth = (nextState, replace) => {
if (!auth.loggedIn()) {
replace({ pathname: '/login' })
}
}
const parseAuthHash = (nextState, replace) => {
console.log('LOG SOMETHING YOU IDIOT');
if (/access_token|id_token|error/.test(nextState.location.hash)) {
auth.parseHash(nextState.location.hash)
}
}
export const makeMainRoutes = () => {
return (
<Route path="/" component={Container} auth={auth}>
<IndexRedirect to="/home" />
<Route path="home" component={Home} onEnter={requireAuth} />
<Route path="login" component={Login} onEnter={parseAuthHash} />
</Route>
)
}
export default makeMainRoutes
出于某种原因,当我登录/登录时,控制台中没有任何内容。我也试着提醒,不会触发。我错过了什么吗?
答案 0 :(得分:1)
我猜你正在使用v4,这已经取消了onEnter:https://reacttraining.com/react-router/web/api/Route
相反,您将使用渲染道具。他们的新文档有一个例子:https://reacttraining.com/react-router/web/example/auth-workflow
以下是它的主要观点:
const PrivateRoute = ({ component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
React.createElement(component, props)
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)