2017-09-23 130 views
0

我正在使用 「react-router」:「^ 4.2.0」, 「react-router-dom」:「^ 4.2.2」, 我想要做的就是當我在一個頁面中提交表單時,它必須指向另一個定義的頁面(組件)。這裏是我的代碼React router「context.router.transitionTo is not a function」

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

任何幫助,將不勝感激

+0

看到這個答案編程導航,反應不建議使用上下文,https://stackoverflow.com/questions/44127739/programatically-navigate-using-react-路由器/ 44128108#44128108 –

+0

我承認Wes Bos在這裏的「對初學者的反應」課程。今天我偶然發現了同樣的問題,你是如何解決你的問題的? – Marecky

+0

這個線程包含了大量有關編程導航的有用信息https://stackoverflow.com/questions/42123261/programmatically-navigate-using-react-router-v4 –

回答

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 
} 
0

既然我們已經可以props下訪問history,我們甚至不需要導入PropTypes了。如果你注意到,當調用this.props.history時,我們甚至不會觸及我們稍後用PropTypes聲明的路由器上下文。只要有下面的代碼是作品:

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