React-router - 如何在 React 中的页面之间传递数据?

IT技术 javascript reactjs react-router
2021-03-26 11:06:03

我正在做一个项目,我必须将数据从一个页面传递到另一个页面。例如,我data在第一页上。

let data = [
  {id:1, name:'Ford', color:'Red'},
  {id:2, name:'Hyundai', color:'Blue'}
]

这是我使用名称呈现此数据列表的第一个组件页面。

class ListDetail extends Component {
    constructor();
    handleClick(data){
    console.log(data);
  }
  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <ul>
          {data.map((data,i) => {
            return <li onClick={this.handleClick.bind(this,data)}>{data.name}</li>
          })}
        </ul>
      </div>
    );
  }
}

我想将此数据传递到下一页,在那里我需要这些数据以及比这更多的数据。我正在使用 React Router 4。任何建议或帮助都会有所帮助。

6个回答

您可以使用 react-router 中的 Link 组件并指定to={}为一个对象,您可以在其中指定路径名作为要到达的路由。然后添加一个变量,例如data保存要传递的值。请参阅下面的示例。

使用<Link />组件:

<Link
  to={{
    pathname: "/page",
    state: data // your data array of objects
  }}
>

使用 history.push()

this.props.history.push({
  pathname: '/page',
    state: data // your data array of objects
})

使用上述任一选项,您现在可以data按照页面组件中的以下内容访问位置对象。

render() {
  const { state } = this.props.location
  return (
    // render logic here
  )
}

您可以在此处的另一个示例中查看如何将值与路由一起传递的示例

如何访问页面组件中的数据?
2021-05-25 11:06:03
您建议使用 Redux,但据我了解,Redux 在切换 URL 时不保存值是否正确?
2021-05-26 11:06:03
还需要确保路由在路由过程中通过props。<Route 精确路径="/path" component={(props) => <View {...props}/>} />
2021-06-03 11:06:03
您还需要在接收器中为 props.match.params.<variablename> 对您传递的参数进行 encodeURIComponent 和 decodeURIComponent 编码,否则,如果您要传递的参数中有正斜杠,React 将不会使用 props 调用构造函数并且不会声明任何错误或控制台输出让您猜测。
2021-06-16 11:06:03
嘿@YuvalLevy,在单页反应应用程序的上下文中,并使用反应路由器在前端管理路由,redux 管理与路由分开的状态。因此,无论路由如何,您都可以使用 redux 中的状态。当然,如果您浏览到您自己的应用程序之外的另一个站点,那就是另外一回事了。
2021-06-18 11:06:03

您可以使用 react-router 的Link组件并执行以下操作:

<Link to={{
  pathname: '/yourPage',
  state: [{id: 1, name: 'Ford', color: 'red'}]
}}> Your Page </Link>

然后访问数据 this.props.location.state

您还可以考虑在整个应用程序 ( https://redux.js.org/ ) 中使用 redux 进行状态管理

或者 如果数组中有很多对象,则可以使用 map 函数。
2021-05-23 11:06:03
@AmitJS94 您可以通过导入组件来传递函数,然后您可以将函数的引用作为道具传递给另一个组件,我认为 state 不会从其他组件调用您的函数,但 props 会这样做。我会留下一个小片段供您理解: <yourComponent yourFunction={this.yourFunction}/>
2021-06-03 11:06:03
此方法在 react-router-dom 版本 6 中不起作用,因为在 v6 中我们没有位置属性,我们可以使用钩子代替,同时将状态传递给其他组件以获取更多详细信息:stackoverflow.com/a/68967670/7312335
2021-06-06 11:06:03
我们可以传递函数吗?
2021-06-07 11:06:03
您在这里将面临的问题是您正在传递对象数组,因此这意味着您无法通过 this.props.location.state.id 或其他方式在目标组件中访问它,您必须像这样访问数组对象.props.location.state[0].id 或 this.props.location.state[0].name 等。
2021-06-14 11:06:03

将数据传递给目标 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;

如何将数据传递到 reactjs 中的另一个组件路由器

登录.jsx

 handleClickSignIn(){
            console.log("come handle click fun");
            this.props.history.push( {pathname: "/welcome",
            state: { employee:"Steven" }});
      
        }

欢迎.jsx

componentDidMount()
{
  console.log(this.props.location.state.employee);
}

假设您的另一个页面是一个组件,您可以将数据作为props传递,该props将在下一页上可用。不过需要注意的是,您必须使用<Link />可用的组件,react-router 4而不是使用<a></a>它会导致整页重新加载,从而导致数据访问丢失。