【问题标题】:ReactRouter 2.0.1 context missing with links缺少链接的 React Router 2.0.1 上下文
【发布时间】:2016-03-24 16:21:24
【问题描述】:

我正在使用带有以下文件的react-router 版本2.0.1

import React, {Component}              from 'react'
import {render}                        from 'react-dom'
import {Link, Router, Route, browserHistory} from 'react-router'

class Home extends Component {

  render() {
    return (
      <div>
        <h1>Home</h1>
      </div>
    )
  }

}

class About extends Component {

  render() {
    return (
      <div>
        <h1>About</h1>
      </div>
    )
  }

}

class Contact extends Component {

  render() {
    return (
      <div>
        <h1>Contact</h1>
      </div>
    )
  }

}

render(
  <section>
    <Link to="/">Home</Link>
    <Link to="/about">About</Link>
    <Link to="/contact">Contact</Link>
    <Router history={browserHistory}>
      <Route path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </Router>,
  </section>,
  document.querySelector('main')
)

当我点击其中一个链接时,我得到:

ReactErrorUtils.js:71 Uncaught TypeError: Cannot read property 'push' of undefined
handleClick @   Link.js:124
ReactErrorUtils.invokeGuardedCallback   @   ReactErrorUtils.js:71
executeDispatch @   EventPluginUtils.js:79
executeDispatchesInOrder    @   EventPluginUtils.js:102
executeDispatchesAndRelease @   EventPluginHub.js:43
executeDispatchesAndReleaseTopLevel @   EventPluginHub.js:54
forEachAccumulated  @   forEachAccumulated.js:23
processEventQueue   @   EventPluginHub.js:259
runEventQueueInBatch    @   ReactEventEmitterMixin.js:18
handleTopLevel  @   ReactEventEmitterMixin.js:34
handleTopLevelWithoutPath   @   ReactEventListener.js:93
handleTopLevelImpl  @   ReactEventListener.js:73
perform @   Transaction.js:136
batchedUpdates  @   ReactDefaultBatchingStrategy.js:62
batchedUpdates  @   ReactUpdates.js:94
dispatchEvent   @   ReactEventListener.js:204

Link.js:124:

this.context.router.push(_location);

知道我错过了什么吗?

编辑:要查找完整示例,您可以克隆此gist

【问题讨论】:

    标签: javascript react-router


    【解决方案1】:

    this.context.router.push 是失败的函数。

    所以要么没有在上下文对象上设置路由器属性,要么没有传递上下文......

    我看到您将 Link 组件作为 Router 组件的对等组件(而不是子组件)。

    context (https://facebook.github.io/react/docs/context.html) 被传递到组件树中,我猜是因为链接在它之外,所以它们无法找到合适的上下文。

    尝试重写应用组件树

    【讨论】:

    • 啊,是的,我需要将每个Link 放在&lt;Route path="/" component={App}&gt;&lt;/Route 中,这样才能传递上下文!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2017-04-28
    • 2017-05-26
    相关资源
    最近更新 更多