Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

reactjs - Cannot read property 'handleClick' of undefined when using map

I am trying to make a table row function like a Link with react-router.

I keep getting the error Cannot read property 'handleClick' of undefined

handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>   
         </tr>
       )
   });
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use arrow function as map callback to preserve component context (otherwise this inside the callback will not point to the component instance):

render(){
   var userNodes = this.props.posts.map((user, i) => {
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>   
         </tr>
       )
   });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...