2017-11-25 16 views
2

バインドされた関数(param)(プロパティを持つsetState())を渡そうとしていますが、このエラーに直面しています。機能のバインドされた関数がプロパティとして渡されましたReact

Cannot read property 'upadateComment' of undefined 

これはindex.jsファイルで私のクラスのスニペット、(機能を持つクラス)

removeComment = (i) => { 
    console.log('removing comment: ' + i); 
    var arr = this.state.comments; 
    arr.splice(i, 1); 
    this.setState({comments: arr}); 
} 

upadateComment = (newText , i) => { 
    console.log('updating comment: ' + i); 
    var arr = this.state.comments; 
    arr[i] = newText; 
    this.setState({comments: arr}); 
} 


eachComment(text, i) { 
    return (
     <Comment        
     key={i} index={i} updateCommentText={this.upadateComment}//here is the problem 
     removeCommentText={this.removeComment}> //and here 
     {text} 
     </Comment> 
    ); 
} 

render() { 
    return (
     <div> 
      {this.state.comments.map(this.eachComment)} 
     </div> 
    ); 
} 

であり、これは(Comment.jsファイル)、それらを呼び出すための場所です

edit =() => { 
    this.setState({editing: true}); 
} 

remove =() => { 
    this.props.removeCommentText(this.props.index); 
    console.log('removing'); 
} 

save =() => { 
    this.props.updateCommentText(this.refs.newText.value , this.props.index); 
    console.log('new Text: '); 
    this.setState({editing: false}); 
} 
+0

「this.state = {};」を定義したコードを更新します。コンストラクタ – Aaqib

答えて

0

eachCommentは関数宣言であるため、間違ったthisコンテキストを参照しています。それをarrow functionに変更することをお勧めします。

eachComment = (text, i) => { 
    return (
     <Comment        
     key={i} index={i} updateCommentText={this.upadateComment} 
     removeCommentText={this.removeComment}> 
     {text} 
     </Comment> 
    ); 
} 
関連する問題