简体   繁体   English

反应ES6类过渡到不起作用

[英]React ES6 Class transitionTo Not Working

Inside Class 内部类

constructor(props, context) {
super(props, context);

someFn = () = {    
    this.context.router.transitionTo('google.com');
}

at the bottom of component 在组件的底部

MyComponent.contextTypes = {
  router: React.PropTypes.func.isRequired
};

I keep getting the error Warning: Failed Context Types: Required context router was not specified in Homepage . 我不断收到错误警告:失败的上下文类型: Homepage中未指定所需的上下文router

When I click on the button to navigate I get the following additional error Uncaught TypeError: Cannot read property transitionTo of undefined 当我单击按钮进行导航时,出现以下附加错误: 未捕获的TypeError:无法读取未定义的属性transitionTo

I've even tried adding the following in the constructor but to no avail 我什至尝试在构造函数中添加以下内容,但无济于事

this.context = context

The vast majority of applications do not need to use context. 绝大多数应用程序不需要使用上下文。 (ref: https://reactjs.org/docs/context.html ) (参考: https : //reactjs.org/docs/context.html

Below should help you => 下面应该可以帮助您=>

import {Component} from 'react';
import PropTypes from 'prop-types';

class MyComponent extends Component {

  static contextTypes = {
    router: PropTypes.object
  };

  onFormSubmit() {
    this.context.router.push('/home');
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit.bind(this)}>
      </form>
    );
  }
}

I asked the same question in react-router github repo and got the answer https://github.com/rackt/react-router/issues/2107 我在react-router github repo中问了同样的问题并得到了答案https://github.com/rackt/react-router/issues/2107

the gist: history is replacement for old router 要点: history是旧router替代品

class Component extends React.Component {
  static contextTypes= {
    history: React.PropTypes.object,
    location: React.PropTypes.object
  }
  render() {
      console.log(this.context.history, this.context.location)
      return null;
  }
}

I tried below and worked correctly. 我在下面尝试并正常工作。 My react-router is 1.0.0-rc3 . 我的react-router1.0.0-rc3

export default class MyComponent extends React.Component {
    static contextTypes = {
        history: React.PropTypes.object
    }
    routeHandler() {
        this.context.history.pushState(null, '/test');
    }
    render() {
        return <button onClick={this.routeHandler.bind(this)} />;
    }
}

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

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