在我的React应用程序中,我正在使用react-router-dom。App.js
我已经设定了我的路线。在那里我有三个组件:/home
、/customerinfo
和/success
。
在主页组件中,我有一个按钮。我想要的是,当我按下按钮时,customerinfo
组件将整页加载,我希望customerinfo
组件中home
组件的状态。这是我的Route
的样子:
<Route
path="/customerInfo"
render={props => <CustomerInfo {...props} />}
/>
但是我无法访问App.js
中home
组件的状态,因此它不起作用。
如何在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;
希望有帮助!!