我有这个代码:
<BrowserRouter>
<Route path="/(:filter)?" component={App} />
</BrowserRouter>
根上的过滤器参数或“”是否应该基于以前的 React 路由器版本在 App 组件的 props 上?
这是我在我的应用程序上的代码:
const App = ({params}) => {
return ( // destructure params on props
<div>
<AddTodo />
<VisibleTodoList
filter={params.filter || 'all'} // i want to git filter param or assign 'all' on root
/>
<Footer />
</div>
);
}
我在控制台上记录了 this.props.match.params 但它没有?帮助?
最佳答案
我假设您正在关注 Redux tutorial on Egghead.io ,因为您的示例代码似乎使用了该视频系列中定义的内容。我在尝试集成 React Router v4 时也卡在了这部分,但最终找到了一个与您所尝试的相差不远的可行解决方案。
⚠️ NOTE: one thing I would check here is that you are using the current version of
react-router-dom
(4.1.1
at the time of this writing). I had some issues with optional filters in the params on some of the alpha and beta versions of v4.
首先,这里的一些答案是不正确的,您确实可以在 React Router v4 中使用可选参数,而不需要正则表达式、多路径、陈旧的语法或使用 <Switch>
组件。
<BrowserRouter>
<Route path="/:filter?" component={App} />
</BrowserRouter>
其次,正如其他人所指出的,React Router v4 不再公开 params
在路由处理程序组件上,而是给我们一个 match
Prop 使用。
const App = ({ match }) => {
return (
<div>
<AddTodo />
<VisibleTodoList filter={match.params.filter || 'all'} />
<Footer />
</div>
)
}
从这里开始,有两种方法可以使您的内容与当前路由保持同步:使用 mapStateToProps
或使用 HoC withRouter
,这两种解决方案已经在 Egghead 系列中讨论过,所以我不会在这里重复它们。
如果您仍然遇到问题,我强烈建议您查看我的该系列已完成应用程序的存储库。
- Here is the commit using the
mapStateToProps
solution - Here is the commit using the
withRouter
soluiton
两者似乎都工作正常(我刚刚测试了它们)。
关于javascript - 如何在 react router dom v4 中获取组件中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44471437/