React-router - 无法读取未定义的 属性 'query'

React-router - Cannot read property 'query' of undefined

我有这个错误: 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 函数时出现问题

我认为问题出在您的 require auth 函数上。

React router 在这里有一个 auth 的例子,https://github.com/rackt/react-router/tree/latest/examples/auth-flow

我会像这样重构函数。

function requireAuth(nextState, replaceState) {
    if (true)
        replaceState({ nextPathname: nextState.location.pathname }, '/login')
}