2017-10-12 128 views
0
constructor() { 
    super(); 



    this.state = { 

     idnum: this.props.match.params.id, 
     pokemon: [], 
     imgurl: '', 
     abilities: [], 
     types: [] 
    }; 

    this.clickHandler = this.clickHandler.bind(this); 
}; 

clickHandler(e) { 

    this.setState({ 
     idnum: this.props.match.params.id 
    }) 
    console.log("passed" , this.props.match.params.id) 
} 

我试图存储this.props.match.params.id这是传过来的道具成React.js this.props我的状态之一的id号.match.params.id在我的componentWillMount函数中起作用,它使用这个ID号从一个API调用一个特定的数据,但是当我尝试将它存储在我的状态时,它给了我那个未定义的匹配。存储作为道具的状态作出反应JS

我需要这让我可以做

<Link to={{ pathname: '/details/' + (parseInt(this.props.match.params.id) - 1) }}><Button onClick = {this.clickHandler }>Prev</Button></Link> 

什么是存储我this.props.match的方式链接到与以前的身份证号码的页面时,页面重新渲染工作。 params.id到我的状态?

+1

请提供[MCVE。 –

+0

当你的应用程序调用构造函数时,this.props不存在。你需要在你的组件装入后设置状态,就像在componentDidMount中 – Cruiser

+0

可能重复[在构造函数中访问道具](https://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-在反应的-时-使用-e)中 –

回答

0

要访问的道具在构造函数中,你可以做到以下几点:

constructor(props) { 
    super(props) 
    this.state = { 
    idnum: props.match.params.id 
    } 
}