我是反应路由器(v4)的新手,我正在按照教程直到这个小问题:
这段代码效果很好
class App extends Component {
render() {
return (
<Router>
<div>
<ul>
<li><Link to="/link/value1" className="nav-link">Value1</Link></li>
<li><Link to="/link/value2" className="nav-link">Value2</Link></li>
<li><Link to="/link/value3" className="nav-link">Value3</Link></li>
</ul>
<hr/>
<Route path="/link/:id" component={Generic}/>
</div>
</Router>
);
}
}
我定义了一个到/ link /:id的路由,其中包含3个链接。然后我声明我的“通用”组件(作为一个函数):
const Generic = ({ match }) => (
<div className="wrapper">
<div className="section">
<div className="container">
<h3>Menu : {match.params.id}</h3>
</div>
</div>
</div>
)
这项工作如预期,没问题。但是现在,我想用ES6类语法声明我的组件,如下所示:
class Generic extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="wrapper">
<div className="section">
<div className="container">
<h3>Menu : {this.props.params.id}</h3>
</div>
</div>
</div>
);
}
}
在这里我有一个错误:无法读取undefined的属性'id'
如何使用ES6类方法访问“match.params.id”属性?
谢谢您的帮助。
使用{this.props.match.params.id}
如果您需要将一些道具传递给组件,请使用以下方法:(例如)
<Route
path='/home'
render={(props) => <Home {...props} user = {this.state.user} />}
/>
在目标组件中,您现在可以使用this.props.user
和this.props.match.params.id
访问prop和router参数。