【发布时间】:2019-07-04 15:26:17
【问题描述】:
我在使用 react-router 的渲染方法渲染的有状态组件中访问 url 参数时遇到问题。我读过,如果我想通过 react-router 将 props 传递给组件,最好的方法是使用 render 函数。
这是我的App 组件,其中包含Link 和Route:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StatefulComponent from './StatefulComponent.jsx';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null
};
}
render () {
return (
<BrowserRouter>
<div className="react-root">
<Link to="/someUrl">I'm a link</Link>
<Route
path='/:url'
render={() => <StatefulComponent value={this.state.value}/>}
/>
</div>
</BrowserRouter>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
当用户点击Link 时,someUrl 应该可以通过道具在StatefulComponent 中访问。但我无法访问有状态组件中的 url 参数:
import React from 'react';
export default class StatefulComponent extends React.Component {
constructor(props) {
super(props);
console.log('URL PARAMS:', props.match.params);
this.state = {}
}
render () {
return (
<div>
{ this.props.value }
</div>
)
}
}
StatefulComponent 的 props 上没有 match 属性。
【问题讨论】:
标签: react-router react-router-dom