[問題] React設計timer問題

看板Ajax作者 (酣酣)時間8年前 (2016/05/11 17:45), 8年前編輯推噓3(309)
留言12則, 6人參與, 最新討論串1/1
小弟剛學React不久,javascript能力也很弱 目前要做一個簡單的timer 以下是程式碼 var count = 0; var TimerModule = React.createClass({ getInitialState: function() { return {value: 0}; }, compenentDidMount: function() { this.Timer = setInterval(this.Timer, 1); }, compenentWillUnmount: function() { clearInterval(this.Timer); }, Timer: function(){ count++; this.setState({ value: count }); }, render: function() { return (<p>{this.state.value}</p>); } }) 畫面一直在0不會動,我的理解是timer更改state後 React就會去更新畫面, 請問各位大大是我理解有誤嗎 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.216.118.24 ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1462959929.A.2DE.html

05/11 18:01, , 1F
你為什麼要把this.Timer給覆寫掉?
05/11 18:01, 1F

05/11 18:03, , 2F
而且你沒有綁定this, 進去應該是找不到setState
05/11 18:03, 2F

05/11 20:11, , 3F
react不用綁定this 這裡的bug是setInterval的參數丟
05/11 20:11, 3F

05/11 20:11, , 4F
錯啦....你丟一個undefined進setInterval幹嘛?
05/11 20:11, 4F

05/11 20:12, , 5F
喔不是undefined 是數字...
05/11 20:12, 5F

05/11 20:12, , 6F
嗯一樓說的沒錯....Timer這個function執行時this是win
05/11 20:12, 6F

05/11 20:12, , 7F
dow 找不到setState
05/11 20:12, 7F

05/11 21:38, , 8F
setInterval會回傳一個number 然後你又把這個number塞到
05/11 21:38, 8F

05/11 21:39, , 9F
this.Timer去 那this.Timer就不見啦...
05/11 21:39, 9F

05/11 22:29, , 10F
component 拼錯了..
05/11 22:29, 10F
GANN....真的是component拼錯惹 想請教一下我這個例子timer要如何綁定阿 一般看到的例子都是匿名後面直接.bind 請問各位大大在寫react都用什麼工具在debug阿? ※ 編輯: e2755699 (61.216.118.24), 05/12/2016 09:11:29

05/12 14:32, , 11F
快上 es6 吧
05/12 14:32, 11F

06/10 00:43, , 12F
ex6 +1 箭頭函式對新手或從真OO 過來的幫助很大
06/10 00:43, 12F
文章代碼(AID): #1NClyvBU (Ajax)