简体   繁体   English

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

[英]React-router - How to pass data between pages in React?

I am working on a project where I have to pass data from one page to another.我正在做一个项目,我必须将数据从一个页面传递到另一个页面。 For example, I have data on the first page.例如,我在第一页上有data

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

Here is the first component page where I render this list of data with the name.这是我使用名称呈现此数据列表的第一个组件页面。

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>
    );
  }
}

I want to pass this data to the next page where I need this data and more data than this.我想将此数据传递到我需要此数据以及比此更多数据的下一页。 I am using React Router 4. Any suggestion or help would be helpful.我正在使用 React Router 4。任何建议或帮助都会有所帮助。

You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to.您可以使用 react-router 中的 Link 组件并将to={}指定为一个对象,您可以在其中指定 pathname 作为要转到的路由。 Then add a variable eg data to hold the value you want to pass on.然后添加一个变量,例如data来保存要传递的值。 See the example below.请参阅下面的示例。

Using the <Link /> component:使用<Link />组件:

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

Using history.push()使用history.push()

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

Using either of the above options you can now access data on the location object as per the below in your page component.使用上述任一选项,您现在可以按照页面组件中的以下内容访问位置对象上的data

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

You can see an example of how to pass a value along with a route in another example here .您可以在此处的另一个示例中查看如何将值与路由一起传递的示例。

You can use react-router's Link component and do the following:您可以使用 react-router 的Link组件并执行以下操作:

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

and then access the data with this.props.location.state然后使用this.props.location.state访问数据

You could also consider using redux for state management in your whole application ( https://redux.js.org/ ).您还可以考虑在整个应用程序 ( https://redux.js.org/ ) 中使用 redux 进行状态管理。

how to pass data into another compoent router in reactjs如何将数据传递到 reactjs 中的另一个组件路由器

Login.jsx登录.jsx

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

welcome.jsx欢迎.jsx

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

Assuming your other page is a component you could pass the data as a prop which will be available on the next page.假设您的另一个页面是一个组件,您可以将数据作为道具传递,该道具将在下一页上可用。 Something to note though, you must use <Link /> component which available in react-router 4 as opposed to using <a></a> which causes a full page reload hence making access of the data lost.不过需要注意的是,您必须使用react-router 4可用的<Link />组件,而不是使用<a></a>导致整页重新加载,从而导致数据访问丢失。

When you want to send one page in one object same code below you must import your page in your object file and again import your page in your destination file same this:当你想在一个对象中发送一个页面时,你必须在你的目标文件中导入你的页面,然后在你的目标文件中再次导入你的页面:

import Home from './componenets/home/home';
import ColdDrink from './componenets/coldDrink/coldDrink';
import HotDrink from './componenets/hotDrink/hotDrink';
import CheaseCake from './componenets/cheaseCake/cheaseCake';
import Lost from './componenets/404/lost';

const link = [
{
name   : "Cold Drink",
link   : "/ColdDrink",
router : <ColdDrink/>
},
{
name   : "Hot Drink",
link   : "/HotDrink",
router : <HotDrink/>
},
{
name   : "chease Cake",
link   : "/CheaseCake",
router : <CheaseCake/>
},
{
name   : "Home",
link   : "/",
router : <Home/>
},
{
name   : "",
link   : "",
router : <Lost/>
}
];

and in your destination file you must map your object...并且在您的目标文件中,您必须映射您的对象...

const links = (this.props.link);
{links.map((item, i) => (
  {item.router}
))}

Best way to pass data to the target Component , just copy paste the code and see the magic, I also explained it in depth.将数据传递给目标 Component 的最佳方式,只需复制粘贴代码即可看到神奇之处,我也对其进行了深入解释。


Let's suppose we have two Components first and second.假设我们有两个组件,第一个和第二个。 The first has the link which will target the second component.第一个具有将针对第二个组件的链接。

The first Component where the link is, by clicking the link you will go to the target path as in my case it is: "/details" .链接所在的第一个组件,通过单击链接,您将转到目标路径,在我的例子中是: "/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>
</>
)
}

Now in the second Component you can access the passed object as:现在在第二个组件中,您可以访问传递的对象:

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>

    </>

    )
}

}

State data, current data is on the Checkout.tsx page, and pass state data on the App.tsx page (using typescript) State 数据,当前数据在Checkout.tsx页面,并在App.tsx页面传递 state 数据(使用 typescript)

Checkout.tsx page Checkout.tsx 页面
 import { useHistory } from 'react-router-dom';
 export default function CheckoutPage() {
    const history = useHistory();
    const data = [
    {
      name: "Ngoc",
      id: 1
    },
    {
      name: "Kevin",
      id: 2
    },
    {
      name: "Jack",
      id: 3
    },
  ];

   history.push({
    pathname: `/app`, /* this path field is based on your project */
    state: data ? data : [] /* pass state data to app page */,
  });
}
App.tsx page App.tsx 页面
 import { useLocation } from 'react-router-dom';
 export default function AppPage() {
    const history = useHistory();
    // use useLocation read data form Checkout page
    const location = useLocation<any>();
    const currentDataFromCheckoutPage = location.state;
    // data pass show here
    console.log('currentDataFromCheckoutPage', currentDataFromCheckoutPage);
}

Its very simple to pass data through navigate.( to another component)通过导航传递数据非常简单。(到另一个组件)

import { useNavigate } from "react-router-dom";从“react-router-dom”导入 { useNavigate };

const navigate=useNavigate()常量导航=useNavigate()

"""suppose you need to pass an "value.id" with navigate,please try this""" """假设你需要通过导航传递一个"value.id",请试试这个"""

onClick={() => {history( /userUpdate,{ state: { id: value.id } })}} onClick={() => {history( /userUpdate,{ state: { id: value.id } })}}

"""then in "userUpdate" component =>""" """然后在 "userUpdate" 组件中 =>"""

import {useLocation} from 'react-router-dom'从 'react-router-dom' 导入 {useLocation}

const { state } = useLocation();常量 { state } = useLocation(); const { id } = state;常量 { id } = state;

console.log(id) """here is the value.id""" console.log(id) """这里是 value.id"""

thank you.谢谢你。

I'm using react-router-dom 6.4.3我正在使用react-router-dom 6.4.3

The following, which seems to work for other/earlier versions, does not work with 6.4.3 :以下似乎适用于其他/早期版本,但不适用于6.4.3

import { Link } from "react-router-dom";

<Link 
  to={{
  pathname: '/details',
  state: stateObj
  }}>Learn More</Link>

A minor change has been made and the below works instead:做了一个小改动,下面的工作代替了:

 <Link 
   to={'/details'}  
   state={stateObj}>Learn More</Link>

Notice how the state object is now outside of the to object?注意 state 对象现在如何位于to对象之外?

In the Details page, you can receive the object as follows:在Details页面,您可以收到如下对象:

import { useLocation } from "react-router-dom";
const DetailsPage: FC<{}> = (props) => {
  const { state } = useLocation();
  //do stuff with state obj
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM