[英]Route Param not working with React
I am trying to use Route params but I cannot get the params. 我正在尝试使用Route参数,但无法获取这些参数。
The page simply shows nothing, seems like undefined or blank. 该页面仅显示任何内容,似乎未定义或空白。
How do I get the param from "wedding/:pageName"? 如何从“ wedding /:pageName”获取参数?
What is missing here? 这里缺少什么? Is it the best way to get params?
这是获取参数的最佳方法吗?
The "pageName" is not ID, is it a problem? “ pageName”不是ID,是否有问题?
Thanks in advance 提前致谢
My App.js 我的App.js
import React, { Component } from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import { connect } from 'react-redux'; import * as actions from '../actions'; import Header from './Header'; import Weddings from './Weddings'; class App extends Component { render() { return ( <div className="container"> <BrowserRouter> <div className="container"> <Header /> <Route path="/wedding/:pageName" component={Wedding} /> </div> </BrowserRouter> </div> ); } } export default connect(null, actions)(App);
Wedding.js Wedding.js
import React from 'react'; import WeddingPage from './weddings/WeddingPage'; const Wedding = () => { return ( <div> <WeddingPage /> </div> ); } export default Wedding;
WeddingPage.js WeddingPage.js
import React, { Component } from 'react'; class WeddingPage extends Component { render() { return ( <div> {this.props.pageName} </div> ); } } export default WeddingPage;
使用React Router,您可以使用this.props.match.params.pageName访问路由器参数。
In your case, first you need to get pageName params in Wedding
component like this.props.match.params.pageName
对于您的情况,首先需要在
Wedding
组件中获取pageName参数,例如this.props.match.params.pageName
and than further pass pageName props to weddingPage component like 并且进一步将pageName道具传递给weddingPage组件,例如
<WeddingPage pageName={this.props.match.params.pageName} />
It's because you aren't passing props through from Wedding
to WeddingPage
. 这是因为您没有将道具从
Wedding
传递到WeddingPage
。
Wedding.js
needs to accept and pass props
to it's child: Wedding.js
需要接受并传递props
给它的孩子:
import React from 'react';
import WeddingPage from './weddings/WeddingPage';
const Wedding = props => {
return (
<div>
<WeddingPage {...props} />
</div>
);
}
export default Wedding;
WeddingPage.js
: WeddingPage.js
:
import React, { Component } from 'react';
class WeddingPage extends Component {
render() {
return (
<div>
{this.props.match.params.pageName}
</div>
);
}
}
export default WeddingPage;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.