如何在我的路由中定义路由。jsx文件捕获__firebase_request_key参数值从一个URL生成的Twitter的单点登录过程后,从他们的服务器重定向?
http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
我尝试了以下路由配置,但:redirectParam没有捕获提到的参数:
<Router>
<Route path="/" component={Main}>
<Route path="signin" component={SignIn}>
<Route path=":redirectParam" component={TwitterSsoButton} />
</Route>
</Route>
</Router>
我花了很长时间才解决这个问题。如果以上都不行,你可以试试这个。我正在使用创建-反应应用程序
需求
react-router-dom ^ 4.3.1“:
解决方案
在指定路由器的位置
<Route path="some/path" ..../>
像这样添加您想要传入的参数名
<Route path="some/path/:id" .../>
在你渲染一些/路径的页面上,你可以指定这个来查看参数名调用id,就像这样
componentDidMount(){
console.log(this.props);
console.log(this.props.match.params.id);
}
在导出默认值的最后
export default withRouter(Component);
记住要包含import
import { withRouter } from 'react-router-dom'
当console.log(this.props)时,你就可以知道传递了什么。玩得开心!
当你使用react route dom时,将用for match清空对象,但如果你执行以下代码,则它将用于es6组件,以及它直接用于函数组件
import { Switch, Route, Link } from "react-router-dom";
<Route path="/profile" exact component={SelectProfile} />
<Route
path="/profile/:profileId"
render={props => {
return <Profile {...props} loading={this.state.loading} />;
}}
/>
</Switch>
</div>
通过这种方式,您可以获得道具并匹配参数和配置文件id
在对es6组件进行了大量研究后,这对我来说很有效。
React路由器v6
来源:在React路由器中获取查询字符串(搜索参数)
使用新的useSearchParams钩子和.get()方法:
const Users = () => {
const [searchParams] = useSearchParams();
console.log(searchParams.get('sort')); // 'name'
return <div>Users</div>;
};
使用这种方法,您可以读取一个或几个参数。
将参数作为一个对象:
如果你需要一次性获得所有的查询字符串参数,那么我们可以像这样使用Object.fromEntries:
const Users = () => {
const [searchParams] = useSearchParams();
console.log(Object.fromEntries([...searchParams])); // ▶ { sort: 'name', order: 'asecnding' }
return <div>Users</div>;
};
阅读更多和现场演示:在React路由器中获取查询字符串(搜索参数)
你可以使用下面的react钩子:
如果url改变,钩子状态会更新
SSR: typeof window === "undefined",只是检查窗口导致错误(尝试一下)
代理对象隐藏实现,因此返回undefined而不是null
这是获取搜索参数为对象的函数:
const getSearchParams = <T extends object>(): Partial<T> => {
// server side rendering
if (typeof window === "undefined") {
return {}
}
const params = new URLSearchParams(window.location.search)
return new Proxy(params, {
get(target, prop, receiver) {
return target.get(prop as string) || undefined
},
}) as T
}
然后像这样把它用作钩子:
const useSearchParams = <T extends object = any>(): Partial<T> => {
const [searchParams, setSearchParams] = useState(getSearchParams())
useEffect(() => {
setSearchParams(getSearchParams())
}, [typeof window === "undefined" ? "once" : window.location.search])
return searchParams
}
如果你的url是这样的:
/app?page=2&count=10
你可以这样读:
const { page, count } = useQueryParams();
console.log(page, count)