我们如何在 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');
});
Route
呈现的组件应该可以访问 this.props.location
、this.props.history
等。我认为您不再需要在 v4 中使用 ref
。尝试做this.props.history.push('/template');
props
传递给与路由匹配的组件?我认为 this GitHub thread 解决了您的问题。
首先,您不需要执行 var r = this;
,因为 if statement
中的 this 指的是回调本身的上下文,因为您使用的是箭头函数,所以它指的是 React 组件上下文。
根据文档:
历史对象通常具有以下属性和方法: length -(数字)历史堆栈中的条目数 action -(字符串)当前操作(PUSH、REPLACE 或 POP)位置 -(对象)当前位置。可能具有以下属性: pathname - (string) URL 搜索的路径 - (string) URL 查询字符串 hash - (string) URL hash 片段状态 - (string) 提供给例如 push( path, state) 当这个位置被压入堆栈时。仅在浏览器和内存历史记录中可用。 push(path, [state]) - (function) 将新条目推送到历史堆栈 replace(path, [state]) - (function) 替换历史堆栈上的当前条目 go(n) - (function) 移动历史堆栈中 n 个条目的指针 goBack() - (function) 等价于 go(-1) goForward() - (function) 等价于 go(1) block(prompt) - (function) 防止导航
因此,在导航时,您可以将道具传递给历史对象,例如
this.props.history.push({
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
})
或类似地用于 Link
组件或 Redirect
组件
<Link to={{
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
}}> My Link </Link>
然后在使用 /template
路由呈现的组件中,您可以访问传递的道具,如
this.props.location.state.detail
另请注意,在使用道具中的历史或位置对象时,您需要将组件与 withRouter
连接。
根据文档:
withRouter 您可以通过 withRouter 高阶组件访问历史对象的属性和最近的
扩展解决方案(由 Shubham Khatri 建议)以与 React 挂钩(16.8 及更高版本)一起使用:
package.json (always worth updating to latest packages)
{
...
"react": "^16.12.0",
"react-router-dom": "^5.1.2",
...
}
使用历史推送传递参数:
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;
使用“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]);
};
对于早期版本:history.push('/[pathToSomeWhere]', yourData);并获取相关组件中的数据,如下所示: this.props.location.state // 它等于 yourData 对于较新的版本,上述方式效果很好,但有一种新方式:history.push({ pathname: ' /[pathToSomeWhere]',状态:你的数据,});并获取相关组件中的数据,如下所示: Class Component this.props.location.state; // 它等于 yourData 函数组件 const location = useLocation();位置.状态; // 它等于 yourData
有时需要使用 Link
或 NavLink
组件而不是使用 history.push
函数。你可以像下面这样使用:
<Link
to={{
pathname: '/[pathToSomeWhere]',
state: yourData
}}
>
...
</Link>
提示:state
键名应在最新版本中使用。
您可以使用,
this.props.history.push("/template", { ...response })
或 this.props.history.push("/template", { response: response })
然后您可以通过以下代码从 /template
组件访问解析的数据,
const state = this.props.location.state
阅读有关 React 的更多信息Session History Management
如果您需要传递 URL 参数
Tyler McGinnis 在他的网站上有一个很棒的帖子解释,Link to the post
以下是代码示例:
在 history.push 组件上:this.props.history.push(`/home:${this.state.userID}`) 在路由器组件上定义路由:
componentDidMount(){
const { myKey } = this.props.match.params
console.log(myKey )
}
使用 Hooks 响应 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>
);
}
useLocation<IState>()
这样你就不必在下一行断言
经过
history.push({pathname:"/yourroute",state: {_id: "0001", name: "AZ"}})
读
import React from 'react';
const YourRoute = props=> {
const { _id, name } = (props.location && props.location.state) || {};
//_id and name will contain the passed data
.
.
.
}
Here 是一个工作示例
我创建了一个自定义 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}`,
});
您可以使用 location
将状态发送到其他组件,如下所示
在您的源组件中
this.props.history.push(pathComponent, sendState);
pathComponent
是接收状态的目标组件
在您的目标组件中,如果您使用类组件,您可以收到这样的状态
Javascript 版本
constructor(props) {
this.state = this.props.location.state
}
打字稿版本
constructor(props: {}) {
const receiveState = this.props.location.state as StateType // you must parse into your state interface or type
this.state = receiveState
}
奖金
如果要重置接收状态。使用 history
替换位置,如下所示
this.props.history({pathName: currentPath, state: resetState})
currentPath
是 目标组件 路径 resetState
是新的值状态,无论你想要什么
const location = useLocation() const data = location.state
要使用 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>
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 router dom version 6.2.1 useHistory() deprecated changed useNavigate()
import { useNavigate } from "react-router-dom";
const navigate = useNavigate()
onClick={() => { navigate('/OtpVerifiy',{mobNo:phoneNumber}) }}
没有必要使用 withRouter。这对我有用:
在您的父页面中,
<BrowserRouter>
<Switch>
<Route path="/routeA" render={(props)=> (
<ComponentA {...props} propDummy={50} />
)} />
<Route path="/routeB" render={(props)=> (
<ComponentB {...props} propWhatever={100} />
)} />
</Switch>
</BrowserRouter>
然后在 ComponentA 或 ComponentB 你可以访问
this.props.history
对象,包括 this.props.history.push 方法。
withRouter
,因为您使用 BrowserRouter
包装了组件,它的工作原理相同。
props
向下传递到包含 history
道具的每个组件中。
要使用 React 16.8+(withHooks),你可以使用这种方式
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
添加信息以获取查询参数。
const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');
有关 URLSearchParams 的更多信息,请查看此链接 URLSearchParams
不定期副业成功案例分享
this.props.history.push('/template',response.data)
不起作用。根据push(path, [state])
的文档,您认为它不应该起作用吗?