Ish*_*arg 143 reactjs react-router
我们如何this.props.history.push('/page')在React-Router v4中传递参数?
.then(response => {
var r = this;
if (response.status >= 200 && response.status < 300) {
r.props.history.push('/template');
});
Run Code Online (Sandbox Code Playgroud)
Shu*_*tri 302
首先,你不需要这样做,var r = this;因为它if statement指的是回调本身的上下文,因为你使用箭头函数指的是React组件上下文.
历史对象通常具有以下属性和方法:
- length - (number)历史堆栈中的条目数
- action - (字符串)当前操作(PUSH,REPLACE或POP)
location - (object)当前位置.可能具有以下属性:
- pathname - (字符串)URL的路径
- search - (字符串)URL查询字符串
- hash - (字符串)URL哈希片段
- state - (字符串)特定于位置的状态,当此位置被推入堆栈时,该状态被提供给例如push(路径,状态).仅适用于浏览器和内存历史记录.
- push(path,[state]) - (function)将新条目推送到历史堆栈
- replace(path,[state]) - (function)替换历史堆栈中的当前条目
- go(n) - (function)通过n个条目移动历史堆栈中的指针
- goBack() - (function)相当于go(-1)
- goForward() - (function)相当于go(1)
- 块(提示) - (功能)防止导航
因此,在导航时,您可以将道具传递给历史对象,例如
this.props.history.push({
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
})
Run Code Online (Sandbox Code Playgroud)
或类似的Link组件或Redirect组件
<Link to={{
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
}}> My Link </Link>
Run Code Online (Sandbox Code Playgroud)
然后在使用/template路径渲染的组件中,您可以访问传递的道具
this.props.location.state.detail
Run Code Online (Sandbox Code Playgroud)
另请注意,在使用道具中的历史记录或位置对象时,您需要连接组件withRouter.
withRouter
您可以
<Route>'s通过withRouter高阶组件访问历史对象的属性和最接近的 匹配.withRouter每次路线改变时都会重新渲染其组件,并使用与<Route>渲染相同的道具props: { match, location, history }.
akh*_*uri 142
扩展解决方案(由 Shubham Khatri 建议)以与 React 挂钩(16.8 及更高版本)一起使用:
package.json (always worth updating to latest packages)
{
...
"react": "^16.12.0",
"react-router-dom": "^5.1.2",
...
}
Run Code Online (Sandbox Code Playgroud)
使用历史推送传递参数:
import { useHistory } from "react-router-dom";
const FirstPage = props => {
let history = useHistory();
const someEventHandler = event => {
history.push({
pathname: '/secondpage',
search: '?query=abc',
state: { detail: 'some_value' }
});
};
};
export default FirstPage;
Run Code Online (Sandbox Code Playgroud)
使用来自“react-router-dom”的 useLocation 访问传递的参数:
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const SecondPage = props => {
const location = useLocation();
useEffect(() => {
console.log(location.pathname); // result: '/secondpage'
console.log(location.search); // result: '?query=abc'
console.log(location.state.detail); // result: 'some_value'
}, [location]);
};
Run Code Online (Sandbox Code Playgroud)
Ame*_*icA 86
对于早期版本:
history.push('/[pathToSomeWhere]', yourData);
Run Code Online (Sandbox Code Playgroud)
并在相关组件中获取数据,如下所示:
this.props.location.state // it is equal to yourData
Run Code Online (Sandbox Code Playgroud)
对于较新的版本,上述方法效果很好,但有一种新方法:
history.push({
pathname: '/[pathToSomeWhere]',
state: yourData,
});
Run Code Online (Sandbox Code Playgroud)
并在相关组件中获取数据,如下所示:
类组件
this.props.location.state; // it is equal to yourData
Run Code Online (Sandbox Code Playgroud)
功能组件
const location = useLocation();
location.state; // it is equal to yourData
Run Code Online (Sandbox Code Playgroud)
有时需要使用Link或NavLink组件而不是使用history.push功能。你可以像下面这样使用:
<Link
to={{
pathname: '/[pathToSomeWhere]',
state: yourData
}}
>
...
</Link>
Run Code Online (Sandbox Code Playgroud)
提示:state密钥名称应在最新版本中使用。
小智 12
使用 Hooks 响应 TypeScript
从一个班
this.history.push({
pathname: "/unauthorized",
state: { message: "Hello" },
});
Run Code Online (Sandbox Code Playgroud)
未经授权的功能组件
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>
);
}
Run Code Online (Sandbox Code Playgroud)
Abd*_*inu 11
history.push({pathname:"/yourroute",state: {_id: "0001", name: "AZ"}})
Run Code Online (Sandbox Code Playgroud)
import React from 'react';
const YourRoute = props=> {
const { _id, name } = (props.location && props.location.state) || {};
//_id and name will contain the passed data
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例
要使用React 16.8(withHooks)功能组件,您可以使用这种方式
我们将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>
Run Code Online (Sandbox Code Playgroud)
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>
)
Run Code Online (Sandbox Code Playgroud)
React router dom 版本 6.2.1
useHistory() 已弃用更改useNavigate()
import { useNavigate } from "react-router-dom";
const navigate = useNavigate()
onClick={() => { navigate('/OtpVerifiy',{mobNo:phoneNumber}) }}
Run Code Online (Sandbox Code Playgroud)
我创建了一个自定义 useQuery 钩子
import { useLocation } from "react-router-dom";
const useQuery = (): URLSearchParams => {
return new URLSearchParams(useLocation().search)
}
export default useQuery
Run Code Online (Sandbox Code Playgroud)
将其用作
const query = useQuery();
const id = query.get("id") as string
Run Code Online (Sandbox Code Playgroud)
按原样发送
history.push({
pathname: "/template",
search: `id=${values.id}`,
});
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用location将状态发送到其他组件,就像这样
在您的源组件中
this.props.history.push(pathComponent, sendState);
Run Code Online (Sandbox Code Playgroud)
pathComponent 是将接收状态的目标组件
在您的目标组件中 ,如果您使用类组件,您可以收到这样的状态
constructor(props) {
this.state = this.props.location.state
}
Run Code Online (Sandbox Code Playgroud)
constructor(props: {}) {
const receiveState = this.props.location.state as StateType // you must parse into your state interface or type
this.state = receiveState
}
Run Code Online (Sandbox Code Playgroud)
如果要重置接收状态。使用history更换位置,这样
this.props.history({pathName: currentPath, state: resetState})
Run Code Online (Sandbox Code Playgroud)
currentPath是目标组件的路径
resetState是任何你想要的新的价值状态
| 归档时间: |
|
| 查看次数: |
149365 次 |
| 最近记录: |