gpt4 book ai didi

react-router-v4 - 如何在路由器外访问 `match.params`?

转载 作者:行者123 更新时间:2023-12-04 00:27:15 24 4
gpt4 key购买 nike

我正在尝试获取 match.params对于我的应用程序的容器。

我尝试使用 withRouter(AppContainer)match.params永远是空的。

// Routes
import React from 'react';
import { Route, Switch, Router } from 'react-router';
import { createBrowserHistory} from 'history';
import AppContainer from './app-container';
...
<Router history={createBrowserHistory()}>
<AppContainer>
<Switch>
...
<Route exact path="/:path1/:path2" component={() => <div>hello</div>} />
...
</Switch>
</AppContainer>
</Router>

// app-container.js
import React from 'react';
import { withRouter } from 'react-router';
const AppContainer = (props) => {
const { match } = props;
console.log(match.params); // This will always be empty
return <div>whatever</div>;
};
export default withRouter(AppContainer);

导航至 /foo/bar .
我期待 match.paramsAppContainer成为 { path1: 'foo', path2: 'bar'} ,但他们总是 {} .

我想是因为 AppContainer位于具有我感兴趣的路线参数的路线之外。

所以,我想知道是否有另一种方法可以在这里做,以便我可以在 AppContainer 中获取路线参数.理想情况下不使用 redux 存储。

最佳答案

简而言之,没有办法使用 match .

在我看来,唯一的方法是使用 matchPath .

import { matchPath, withRouter } from 'react-router';

const Test = ({ location }) => {
/*
`matchPath` will return `null` if it doesn't match the path format.
If it matches, it will return some object with parameters put into it
nicely like `match.params`.
*/
matchPath(location.search, { path: '/:path1/:path2' });
};
export default withRouter(Test);

关于react-router-v4 - 如何在路由器外访问 `match.params`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com