如何通过响应路由器将道具传递到另一页面?

时间:2019-08-16 11:44:32

标签: reactjs react-router-dom

在我的React应用程序中,我正在使用react-router-dom。在App.js中,我设定了路线。我有三个部分:/home/customerinfo/success

在home组件中,我有一个按钮。我想要的是当我按下按钮时,customerinfo组件将以整页加载,并且我希望home组件中的customerinfo组件处于状态。这就是我的Route的样子:

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

但是我无法访问homeApp.js组件的状态,因此它不起作用。

如何获取homecustomerinfo组件的状态?

我是React的新手。请帮助我。

1 个答案:

答案 0 :(得分:0)

使用redux为复杂的应用程序传递数据。

但是,如果您只想坚持使用react,则可以使用props将数据传递给Redirect Component。

单击CustomerInfo按钮时,来自home控制器的数据将向下传递到customerInfo组件。

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;

希望有帮助!

相关问题