我正在使用React.js网络应用,由于某些原因我无法传递网址参数。
示例如下所示:
路线:
eval
第二视图组件
import React from "react";
import {BrowserRouter, Route, Switch, Redirect} from 'react-router-dom';
import Helloworld from './components/helloworld/helloworld.component';
import SecondView from './components/secondview/secondview.component';
import ThirdView from "./components/thirdview/thirdview.component";
const AppRoutes = () => (
<BrowserRouter>
<Switch>
<Route exact path='/' component={Helloworld}/>
<Route path='/secondview' component={SecondView}/>
<Route path='/thirdview' component={ThirdView}/>
<Route path='/thirdview/:number' component={ThirdView}/>
<Redirect from='*' to='/' />
</Switch>
</BrowserRouter>
);
export default AppRoutes;
Thirdview comopnent:
import React from 'react';
import {Link, withRouter} from 'react-router-dom';
class SecondView extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("I am being called SecondView component...");
}
render() {
return (
<div className={"boxDiv"}>
<p>Second View</p>
<Link to={{pathname: '/thirdview/7'}}> GO to third view with parameter value. </Link>
</div>
);
}
}
export default withRouter(SecondView);
我想要的是能够在我的第三视图组件上获得/:数字值!任何人都知道如何在React.js中实现这样的事情?还有其他方法吗?
我得到的是空物!
答案 0 :(得分:0)
我认为应该是:
{this.props.match.params.number}
而不是
{this.props.params.number}
并且您在ThirdView和SecondView上不需要withRouter
,因为已经传递给Route
。
编辑:
由于您要为/thirdview
和/thirdview/7
呈现相同的组件,请使用可选的param matcher
<Switch>
<Route exact path='/' component={Helloworld}/>
<Route path='/secondview' component={SecondView}/>
<Route path='/thirdview/:number?' component={ThirdView}/>
<Redirect from='*' to='/' />
</Switch>