我有这个错误:
Cannot read property 'query' of undefined
当我导航到/ dashboard
app.jsx就像这样
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link } from 'react-router'
import { createHistory } from 'history'
const App = React.createClass({
getInitialState() {
return {
loggedIn: false
}
},
render() {
return (
<div>
<ul>
<li>
{this.state.loggedIn ? (
<Link to="/logout">Log out</Link>
) : (
<Link to="/login">Sign in</Link>
)}
</li>
<li><Link to="/dashboard">Dashboard</Link> (authenticated)</li>
</ul>
</div>
)
}
})
const Dashboard = React.createClass({
render() {
return (
<div>
<h1>Dashboard</h1>
<p>You made it!</p>
</div>
)
}
})
const Login = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState() {
return {
error: false
}
},
render() {
return (
<div>Login Form goes here!</div>
)
}
})
function requireAuth(nextState, replace) {
if (true) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname },
query: '',
})
}
}
var history = createHistory()
render((
<Router history={history}>
<Route path="/" component={App}>
<Route path="login" component={Login} />
<Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
</Route>
</Router>
), document.getElementById('main'))
有什么建议吗?
更新:
调用replace
函数时会出现问题
答案 0 :(得分:9)
我认为问题是你需要auth功能。
React路由器在这里有一个auth示例,https://github.com/rackt/react-router/tree/latest/examples/auth-flow
我会像这样重构函数。
function requireAuth(nextState, replaceState) {
if (true)
replaceState({ nextPathname: nextState.location.pathname }, '/login')
}