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



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

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

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

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

如何在customerinfo中获取home组件的状态?

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

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

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

单击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;

希望有帮助!!

相关内容

最新更新