我们如何在React-Router v4中通过this.props.history.push('/page')传递参数?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
我们如何在React-Router v4中通过this.props.history.push('/page')传递参数?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
当前回答
For the earlier versions: history.push('/[pathToSomeWhere]', yourData); And get the data in the related component just like below: this.props.location.state // it is equal to yourData For the newer versions the above way works well but there is a new way: history.push({ pathname: '/[pathToSomeWhere]', state: yourData, }); And get the data in the related component just like below: Class Component this.props.location.state; // it is equal to yourData Function Component const location = useLocation(); location.state; // it is equal to yourData
有时需要使用Link或NavLink组件,而不是使用历史记录。推动作用。你可以用下面的like:
<Link
to={{
pathname: '/[pathToSomeWhere]',
state: yourData
}}
>
...
</Link>
提示:状态键名称应在最新版本中使用。
其他回答
添加信息以获取查询参数。
const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');
有关URLSearchParams的更多信息,请查看此链接 URLSearchParams
For the earlier versions: history.push('/[pathToSomeWhere]', yourData); And get the data in the related component just like below: this.props.location.state // it is equal to yourData For the newer versions the above way works well but there is a new way: history.push({ pathname: '/[pathToSomeWhere]', state: yourData, }); And get the data in the related component just like below: Class Component this.props.location.state; // it is equal to yourData Function Component const location = useLocation(); location.state; // it is equal to yourData
有时需要使用Link或NavLink组件,而不是使用历史记录。推动作用。你可以用下面的like:
<Link
to={{
pathname: '/[pathToSomeWhere]',
state: yourData
}}
>
...
</Link>
提示:状态键名称应在最新版本中使用。
我创建了一个自定义useQuery钩子
import { useLocation } from "react-router-dom";
const useQuery = (): URLSearchParams => {
return new URLSearchParams(useLocation().search)
}
export default useQuery
使用它作为
const query = useQuery();
const id = query.get("id") as string
就这样发送
history.push({
pathname: "/template",
search: `id=${values.id}`,
});
Pass
history.push({pathname:"/yourroute",state: {_id: "0001", name: "AZ"}})
Read
import React from 'react';
const YourRoute = props=> {
const { _id, name } = (props.location && props.location.state) || {};
//_id and name will contain the passed data
.
.
.
}
下面是一个工作示例
带有钩子的React TypeScript
来自班级
this.history.push({
pathname: "/unauthorized",
state: { message: "Hello" },
});
未经授权的功能组件
interface IState {
message?: string;
}
export default function UnAuthorized() {
const location = useLocation();
const message = (location.state as IState).message;
return (
<div className="jumbotron">
<h6>{message}</h6>
</div>
);
}