【发布时间】:2017-09-13 09:03:40
【问题描述】:
我正在使用 React Router V4 遵循 React for Beginner 教程。但是我无法在组件中获取参数。这是我的代码的一部分。
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}`)
}
}
在我的 App 组件中,我无法获取 storeId。
//storeId is undefine
this.props.match.params.storeId
我的代码有什么问题?
【问题讨论】:
-
能否提供整个 StorePicker 组件文件?
-
@AnkitParikh 我现在更新了我的代码
-
必须是
<Route path='/store/:storeId' component={App} />吗? -
@bennygenel 不,这只是一个实践项目
-
我想我不清楚。我想说,这可能与您在路径上缺少斜线有关。
path='store/:storeId'可能需要为path='/store/:storeId'
标签: reactjs react-router