我们如何在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');
});
当前回答
我创建了一个自定义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}`,
});
其他回答
添加信息以获取查询参数。
const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');
有关URLSearchParams的更多信息,请查看此链接 URLSearchParams
要使用React 16.8+(带hooks),您可以使用这种方式
import React from 'react';
import { useHistory } from 'react-router-dom';
export default function SomeFunctionalComponent() {
let history = useHistory(); // should be called inside react component
const handleClickButton = () => {
"funcionAPICALL"
.then(response => {
if (response.status >= 200 && response.status < 300) {
history.push('/template');
});
}
return ( <div> Some component stuff
<p>To make API POST request and redirect to "/template" click a button API CALL</p>
<button onClick={handleClickButton}>API CALL<button>
</div>)
}
来源这里阅读更多https://reacttraining.com/react-router/web/example/auth-workflow
要使用React 16.8(带hooks)功能组件,您可以使用这种方式 我们发送PhoneNumber到Next Page Login.js
import { useHistory } from 'react-router-dom';
const history = useHistory();
const handleOtpVerify=(phoneNumber)=>
{
history.push("/OtpVerifiy",{mobNo:phoneNumber})
}
<button onClick={handleOtpVerify}> Submit </button>
OtpVerify.js
import useLocation from 'react-router-dom';
const [phoneNumber, setphoneNumber] = useState("")
useEffect(() => {
setphoneNumber(location.state.mobNo)
}, [location]);
return (
<p>We have sent Verification Code to your</p>
<h1>{phoneNumber}</h1>
)
React路由器dom版本6.2.1 useNavigate()已弃用
import { useNavigate } from "react-router-dom";
const navigate = useNavigate()
onClick={() => { navigate('/OtpVerifiy',{mobNo:phoneNumber}) }}
我创建了一个自定义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}`,
});
带有钩子的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>
);
}