作者e2755699 (酣酣)
看板Ajax
標題[問題] React設計timer問題
時間Wed May 11 17:45:27 2016
小弟剛學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://webptt.com/m.aspx?n=bbs/Ajax/M.1462959929.A.2DE.html
1F:推 davidsky: 你為什麼要把this.Timer給覆寫掉? 05/11 18:01
2F:→ davidsky: 而且你沒有綁定this, 進去應該是找不到setState 05/11 18:03
3F:→ mrbigmouth: react不用綁定this 這裡的bug是setInterval的參數丟 05/11 20:11
4F:→ mrbigmouth: 錯啦....你丟一個undefined進setInterval幹嘛? 05/11 20:11
5F:→ mrbigmouth: 喔不是undefined 是數字... 05/11 20:12
6F:→ mrbigmouth: 嗯一樓說的沒錯....Timer這個function執行時this是win 05/11 20:12
7F:→ mrbigmouth: dow 找不到setState 05/11 20:12
8F:→ rarex: setInterval會回傳一個number 然後你又把這個number塞到 05/11 21:38
9F:→ rarex: this.Timer去 那this.Timer就不見啦... 05/11 21:39
10F:推 No: component 拼錯了.. 05/11 22:29
GANN....真的是component拼錯惹
想請教一下我這個例子timer要如何綁定阿
一般看到的例子都是匿名後面直接.bind
請問各位大大在寫react都用什麼工具在debug阿?
※ 編輯: e2755699 (61.216.118.24), 05/12/2016 09:11:29
11F:推 windleaf: 快上 es6 吧 05/12 14:32
12F:→ dlikeayu: ex6 +1 箭頭函式對新手或從真OO 過來的幫助很大 06/10 00:43