简体   繁体   中英

react-router this is undefined

Uncaught TypeError: Cannot read property 'dispatch' of undefined

This occurs in ReactRouter.js in handleLocationChange:

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

This is downstream from my call to

this.context.transitionTo('something');

where 'something' is one of my defined routes. Why would 'this' be undefined?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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