最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React call component's method from nested function in render method - Stack Overflow

programmeradmin3浏览0评论

I would like to call the method updateCurrentThread onCLick, however I'm getting following error:

Uncaught TypeError: Cannot read property 'updateCurrentThread' of undefined

updateCurrentThread: function(thread) {
  this.setState({
  currentThread: thread
 }).bind(this);
},


render: function () {
  var threads = this.state.data.map(function (thread) {
    var boundClick = this.updateCurrentThread.bind(this, i);
    let time = getThreadDate(thread.timestamp);
    return (
      <div className="row thread" key={thread.threadID}>
        <ThreadParticipants onClick={boundClick} key={i} className="small-2 small-centered columns" ids={thread.participantIDs}/>
      </div>
  );
})

I would like to call the method updateCurrentThread onCLick, however I'm getting following error:

Uncaught TypeError: Cannot read property 'updateCurrentThread' of undefined

updateCurrentThread: function(thread) {
  this.setState({
  currentThread: thread
 }).bind(this);
},


render: function () {
  var threads = this.state.data.map(function (thread) {
    var boundClick = this.updateCurrentThread.bind(this, i);
    let time = getThreadDate(thread.timestamp);
    return (
      <div className="row thread" key={thread.threadID}>
        <ThreadParticipants onClick={boundClick} key={i} className="small-2 small-centered columns" ids={thread.participantIDs}/>
      </div>
  );
})
Share Improve this question asked Feb 21, 2016 at 23:10 Wojciech KulmaWojciech Kulma 6,4463 gold badges19 silver badges28 bronze badges 4
  • this is referring to the function scope of the function that is the first parameter to map. Use thread => { } instead of function(){} – walkerrandophsmith Commented Feb 21, 2016 at 23:15
  • Looking into it... :) – walkerrandophsmith Commented Feb 21, 2016 at 23:29
  • Here's my entire react file: pastebin./Qs1uGiRk – Wojciech Kulma Commented Feb 21, 2016 at 23:30
  • I just answered a similar question relating to this references inside the map closure; this answer should assist you stackoverflow./a/35534177/4206756 – Hypaethral Commented Feb 21, 2016 at 23:58
Add a ment  | 

1 Answer 1

Reset to default 7

The this inside your function is scoped to the function, not the ponent. If you are able to use ES6 arrow functions, which are lexically scoped, then your current approach will work. Before arrow functions, people would store the ponent this in a variable (e.g. var self = this) and then self.updateCurrentThread.

发布评论

评论列表(0)

  1. 暂无评论