将数据传递给目标 Component 的最佳方式,只需复制粘贴代码即可看到神奇之处,我也对其进行了深入解释。
请记住:在 react-router-dom v6 中,您可以使用钩子代替。
版本 5.X
假设我们有两个组件,第一个和第二个。第一个具有指向第二个组件的链接。
链接所在的第一个组件,通过单击链接,您将转到目标路径,在我的情况下是:"/details"
。
import React from 'react';
import {Link} from 'react-router-dom';
export default function firstComponent() {
return(
<>
<Link to={{
pathname: '/details',
state: {id: 1, name: 'sabaoon', shirt: 'green'}
}} >Learn More</Link>
</>
)
}
现在在第二个组件中,您可以通过以下方式访问传递的对象:
import React from 'react'
export default class Detials extends React.Component{
constructor(props){
super(props);
this.state={
value:this.props.location.state,
}
}
alertMessage(){
console.log(this.props.location.state.id);
}
render(){
return (
<>
{/* the below is the id we are accessing */}
hay! I am detail no {this.props.location.state.id} and my name is
{this.props.location.state.name}
<br/>
<br/>
{/* press me to see the log in your browser console */}
<button onClick={()=>{this.alertMessage()}}>click me to see log</button>
</>
)
}
}
注意:在 react-router-dom 的第 6 版中,上述方法不适用于类组件,尽管您可以通过 useLocation 钩子使用 react 的功能组件,然后您可以通过另一个组件中的该位置绘制状态对象。
版本 6
如何使用 react-router-dom 的 hooks v6 实现相同的功能
假设我们有两个功能组件,第一个组件 A,第二个组件 B。组件 A 想要与组件 B 共享数据。
钩子的用法:(useLocation,useNavigate)
import {Link, useNavigate} from 'react-router-dom';
function ComponentA(props) {
const navigate = useNavigate();
const toComponentB=()=>{
navigate('/componentB',{state:{id:1,name:'sabaoon'}});
}
return (
<>
<div> <a onClick={()=>{toComponentB()}}>Component B<a/></div>
</>
);
}
export default ComponentA;
现在我们将获取组件 B 中的数据。
import {useLocation} from 'react-router-dom';
function ComponentB() {
const location = useLocation();
return (
<>
<div>{location.state.name}</div>
</>
)
}
export default ComponentB;