2017-09-13 44 views
0

我正在使用React Router V4來學習React for Beginner教程。但是我無法在我的組件中獲得我的參數。這裏是我的代碼的一部分。React路由器V4無法獲得匹配參數

const Root =() => { 
return (
    <BrowserRouter> 
    <div> 
     <Switch> 
      <Route exact path='/' component={StorePicker} /> 
      <Route Path='store/:storeId' component={App} /> 
      <Route component={NotFound} /> 
     </Switch> 
    </div> 
    </BrowserRouter> 
) 
} 

StorePicker組件:

class StorePicker extends React.Component { 
    render() { 
     return (
      <form className="store-selector" onSubmit={(e) => this.goToStore(e)}> 
       <h2>Please Enter A Store</h2> 
       <input type="text" ref={(input) => { this.storeInput= input; }} defaultValue={getFunName()} placeholder="Store Name" required/> 
       <button type="submit">Visit Store</button> 
      </form> 
     ) 
    } 

    goToStore(event) { 
     event.preventDefault() 
     const storeInput = this.storeInput.value 
     console.log(storeInput) 
     this.props.history.push(`store/${storeInput}`) 
    } 

} 

而且在我的應用程序組件,我不能得到STOREID。

//storeId is undefine 
this.props.match.params.storeId 

我的代碼有什麼問題?

+0

你能提供全StorePicker組件文件:

我從反應路由器網站把這個直接? –

+0

@AnkitParikh我已經更新了我的代碼 –

+0

它是否需要''? – bennygenel

回答

0

陣營路由器4已經重新vamped:

的路由器環境不再注入自動道具(如果我沒記錯,這是取決於你如何規定的情況下如何反應的路由器3的工作,或路由器呈現的組件)。

試試這個:

import { withRouter } from 'react-router';

導出您的組件時,將它包裝:

withRouter(MyComponent)

這應該正確注入您正在尋找這樣的道具他們arent不確定。

https://reacttraining.com/react-router/web/api/withRouter

+0

所以我應該導出我的應用程序組件像導出默認與路由器(應用程序)? –

+0

我不是很確定,但'withRouter'是用於與路由沒有直接關係的組件。而不是傳遞道具給每個孩子,你可以使用'withRouter' – bennygenel

+0

是的,所以聲明你的類在頂部,例如:class App extends React.Component。然後在底部'出口默認與路由器(應用程序)',授予我不知道你的應用程序設置,但我假設這是你的問題,爲什麼它的未定義 – Marrs