简体   繁体   中英

how to pass props one page to another page via react router?

In my React app I'm using react-router-dom. In App.js I have set my routes. There I have three components: /home , /customerinfo and /success .

In the home component I have a button. What I want is that when I press the button, the customerinfo component will load in full page and I want the state of the home component in the customerinfo component. This is what my Route looks like:

<Route
  path="/customerInfo"
  render={props => <CustomerInfo {...props} />}
/>

But I don't have access of the state of the home component in App.js , so it's not working.

How can I get the state of the home component in customerinfo ?

I'm new in React. Please help me.

Use redux to pass data for complex application.

But if you want to stick around using react only then you could pass data using props to Redirect Component.

When CustomerInfo button is clicked data from home Controller is passed down to customerInfo component.

import React from "react";
import { BrowserRouter as Router, Route, Link, Redirect } from "react-router-dom";

function BasicExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
        </ul>
        <hr />

        <Route exact path="/" component={Home} />
        <Route path="/customerinfo" component={CustomerInfo} />
      </div>
    </Router>
  );
}

class Home extends React.Component {
  state = {
    redirect: false,
    data: 'data passed through home route to customer info route'
  };
  handleClick = () => {
    this.setState({
      redirect: true
    })
  }
  render () {
    if (this.state.redirect) {
      return <Redirect to={{
        pathname: '/customerinfo',
        state: { data: this.state.data }
      }} />
    } else {
      return (
        <div>
          <h2>Home</h2>
          <button onClick={this.handleClick}>CustomerInfo</button>
        </div>
      );
    }
  }
}

function CustomerInfo({ location }) {
  console.log(location)
  return (
    <div>
      <h2>{location.state.data}</h2>
    </div>
  );
}

export default BasicExample;

Hope that helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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