我正在使用 React、React-Router (v5) 和 Redux 构建一个应用程序,并且想知道如何访问父路由中当前 URL 的参数。
这是我的条目,router.js
:
<Wrapper>
<Route exact path="/login" render={(props) => (
<LoginPage {...props} entryPath={this.entryPath} />
)} />
<Route exact path="/" component={UserIsAuthenticated(HomePage)} />
<Route exact path="/about" component={UserIsAuthenticated(AboutPage)} />
<Route path="/projects" component={UserIsAuthenticated(ProjectsPage)} />
</Wrapper>
这就是我的 ProjectsPage
组件:
class ProjectsPage extends PureComponent {
componentDidMount() {
this.props.fetchProjectsRequest()
}
render() {
console.log(this.props.active)
if (this.props.loading) {
return <Loading />
} else {
return (
<Wrapper>
<Sidebar>
<ProjectList projects={this.props.projects} />
</Sidebar>
<Content>
<Route exact path="/projects" component={ProjectsDashboard} />
<Switch>
<Route exact path="/projects/new" component={ProjectNew} />
<Route exact path="/projects/:id/edit" component={ProjectEdit} />
<Route exact path="/projects/:id" component={ProjectPage} />
</Switch>
</Content>
</Wrapper>
)
}
}
}
const enhance = connect(
(state, props) => ({
active: props.match,
loading: projectSelectors.loading(state),
projects: projectSelectors.projects(state)
}),
{
fetchProjectsRequest
}
)
export default withRouter(enhance(ProjectsPage))
问题是,我的 render
方法中的 console.log
输出是 {"path":"/projects","url":"/projects","isExact":false,"params":{}}
尽管 URL 是 http://localhost:3000/projects/14
。
我想向我的 ProjectList
添加一个 ID
属性以突出显示当前选定的项目。
我可以将项目的 ID 保存在我的 ProjectPage
组件内的存储中,但我认为这会有点令人困惑,特别是因为 URL 实际上包含信息 - 那么我为什么要写商店里有什么东西吗?
另一种(坏?)方法是自己解析位置对象并获取ID,但我认为有一个 react-router
/react-router-redux
获取此时我忽略的参数的方法。
最佳答案
@Kyle 从技术角度很好地解释了问题。 我将只专注于解决该问题。
您可以使用matchPath
来获取所选项目的id
。
matchPath - https://reacttraining.com/react-router/web/api/matchPath
This lets you use the same matching code that uses except outside of the normal render cycle, like gathering up data dependencies before rendering on the server.
这种情况下的用法非常简单。
1 使用matchPath
// history is one of the props passed by react-router to component
// @link https://reacttraining.com/react-router/web/api/history
const match = matchPath(history.location.pathname, {
// You can share this string as a constant if you want
path: "/articles/:id"
});
let articleId;
// match can be null
if (match && match.params.id) {
articleId = match.params.id;
}
2 在渲染中使用articleId
{articleId && (
<h1>You selected article with id: {articleId}</h1>
)}
我构建了一个简单的演示,您可以使用它在项目中实现相同的功能。
演示: https://codesandbox.io/s/pQo6YMZop
我认为这个解决方案非常优雅,因为我们使用官方的 react-router
API,它也用于路由器中的路径匹配。我们在这里也不使用 window.location
,因此如果您还导出原始组件,测试/模拟将会很容易。
关于reactjs - 如何获取父路由组件中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45487779/