React router" context.router.transitionTo不是一个函数"

时间:2017-09-23 04:12:24

标签: reactjs react-router react-redux

我正在使用 " react-router":" ^ 4.2.0", " react-router-dom":" ^ 4.2.2", 我想要做的就是当我在一个页面中提交表单时,它必须指向另一个定义的页面(组件)。这是我的代码

FormValue.js

import React from "react";

class FormValues extends React.Component{
  gotoStore(e){
    e.preventDefault();
    let id = this.storeInput.value;
    this.context.router.transitionTo(`${id}`);
 }

render(){
    return (
            <form onSubmit={(e) => this.gotoStore(e)}>
                <input type="text" placeholder="enter your name" 
                 ref={(input) => {this.storeInput = input}}/>
                <button type="submit">Submit</button>
            </form>
    )
}
}

FormValues.contextTypes = {
 router: React.PropTypes.object
}

 export default FormValues;

index.js

  import React from "react";
  import { render } from 'react-dom';
  import {BrowserRouter, Route} from "react-router-dom";
  import ReactDom from "react-dom";
  import App from './App';
  import FormValues from './FormValues';

  const Root = () => {
   return (
    <BrowserRouter>
        <div>
            <Route path="/" exact component={FormValues}/>
            <Route path="/:id" exact component={App}/>

        </div>
    </BrowserRouter>
   )
  }

  ReactDom.render(<Root/>, document.getElementById('root'));

我收到错误enter image description here

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:1)

我的解决方案是:

import { PropTypes } from 'prop-types';

goToStore(e) {
 e.preventDefault();
 const storeId = this.storeInput.value;
 this.props.history.push(`store/${storeId}`);
}

StorePicker.contextTypes = {
  router: PropTypes.object
}

答案 1 :(得分:0)

由于我们已经可以访问history下的props,我们甚至不再需要导入PropTypes了。如果您注意到,在致电this.props.history时,我们甚至没有触及路由器上下文,我们稍后会使用PropTypes声明。只需使用以下代码即可:

goToStore(e) {
 e.preventDefault();
 const storeId = this.storeInput.value;
 this.props.history.push(`store/${storeId}`);
}

答案 2 :(得分:0)

import { PropTypes } from "prop-types";

  goToStore(event) {

     event.preventDefault();

     const storeId = this.storeInput.value;

     this.context.router.history.push(`/store/${storeId}`);

  };

  StorePicker.contextTypes = {

    router: function contextType(){

     return PropTypes.object;

    }
  }