如何通过Reaction路由器将道具从一页传到另一页? [英] how to pass props one page to another page via react router?
本文介绍了如何通过Reaction路由器将道具从一页传到另一页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Reaction应用程序中,我使用的是REACT-ROUTER-DOM。在App.js
中,我已经设置了我的路线。我有三个组件:/home
、/customerinfo
和/success
。
在Home组件中,我有一个按钮。我想要的是,当我按下按钮时,customerinfo
组件将在整个页面中加载,并且我希望home
组件在customerinfo
组件中的状态。我的Route
是这样的:
<Route
path="/customerInfo"
render={props => <CustomerInfo {...props} />}
/>
但我无法访问App.js
中home
组件的状态,因此它不工作。
如何获取customerinfo
中home
组件的状态?
我的反应是新手。请帮帮我。
推荐答案
使用Redux为复杂应用程序传递数据。
但如果您只想继续使用Reaction,则可以使用道具将数据传递给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;
希望这会有帮助!
这篇关于如何通过Reaction路由器将道具从一页传到另一页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文