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

时间:2016-01-26 20:52:58

标签: reactjs react-router

我有这个错误: 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'))
  • ReactDOM v0.14.6
  • React(with addons)v0.14.6
  • react-router:2.0.0-rc5(保存在node_modules / react-router下的umd目录下)

有什么建议吗?

更新: 调用replace函数时会出现问题

1 个答案:

答案 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')
}