2017-06-19 99 views
5

我'新反应路由器(V4),我是按照教程,直到这个小问题:React-router:如何将“匹配”对象传递给声明为ES6类的组件?

此代码工作得很好

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> 
); 
} 
} 

我定义了一个路线/链接/:ID有3个链接。然后我声明我的“通用”组件如下(作为函数):

const Generic = ({ match }) => (
<div className="wrapper"> 
    <div className="section"> 
     <div className="container"> 
      <h3>Menu : {match.params.id}</h3> 
     </div> 
    </div> 
</div> 
) 

这个工作正如所料,没有问题。但现在,我想用ES6类syntaxe这样的声明我的组件:

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> 
    ); 
} 
} 

在这里,我有一个错误:无法未定义

读取属性“ID”我怎样才能访问使用ES6类方法的“match.params.id”属性?

谢谢你的帮助。

+1

好吧,我正在寻找错误的对象。上面的例子工作正常,如果我将this.props.params.id更改为this.props.match.params.id – Cabrinha

回答

11

使用{this.props.match.params.id}