简体   繁体   English

react-router这是未定义的

[英]react-router this is undefined

Uncaught TypeError: Cannot read property 'dispatch' of undefined 未捕获的TypeError:无法读取未定义的属性“ dispatch”

This occurs in ReactRouter.js in handleLocationChange: 这发生在ReactRouter.js中的handleLocationChange中:

      handleLocationChange: function handleLocationChange(change) {
        this.dispatch(change.path, change.type);
      },

This is downstream from my call to 这是我打电话给的下游

this.context.transitionTo('something'); this.context.transitionTo('something');

where 'something' is one of my defined routes. 其中“某物”是我定义的路线之一。 Why would 'this' be undefined? 为什么“ this”是不确定的?

Here is my component calling the code: 这是我的组件调用代码:

var React = require("react");
var Router = require("react-router");
var { Link } = Router;
var Button = require('core-ui').Button;

var AppointmentsHeader = React.createClass({
    mixins: [React.addons.PureRenderMixin],
    contextTypes: {
        router: React.PropTypes.func
    },

    render: function () {
        console.log("AppointmentsHeader:render");
        var router = this.context.router;
        // default to hidden
        var displayClassInline = "appointments-hide"; // hide/show this element if the current page is Landing Page

        if (this.props.currentState.get('currentState') === "landingPage")
        {
            displayClassInline = "appointments-block-show";
        }
        return (
            <div className={"appointments-header cv-grid " + displayClassInline}>
                <div className="appointments-title">Appointments</div>
                <Button label="Create Appointment Event" style="primary" onClick={this._onClick}/>
            </div>
        );
    },
    _onClick: function() {
        console.log("AppointmentsHeader 'Create Appointment Event' button clicked");
        var newStatus = this.props.currentState.set('currentState', "CreateAppointment");
        this.props.handleChange(newStatus);
        this.context.transitionTo('createAppointmentsEvent');
    }
});

module.exports = AppointmentsHeader;

This line: 这行:

this.context.transitionTo('createAppointmentsEvent')

Should be: 应该:

this.context.router.transitionTo('createAppointmentsEvent');

or 要么

this.transitionTo('createAppointementsEvent')

You are accessing the singleton router two different ways in your example: 在示例中,您将通过两种不同的方式访问单例路由器:

  • The Navigation mixin 导航混合
  • The Router that is injected via the contextTypes hash 通过contextTypes哈希注入的路由器

The API Is very confusing right now because Ryan went down one road (getting rid of mixins entirely) and then decided to "undepricate" the mixins. 该API现在非常混乱,因为Ryan走了一条路(完全摆脱了mixins),然后决定“滥用” mixins。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM