2017-07-18 34 views
0

我正在學習React,並且給出了一個簡單的挑戰:點擊一個按鈕時計數增加。如何增加React中的狀態?

問題是我的組件似乎把數字看作字符串並將它們連接起來,而不是增加它們。例如,如果我的起始數字是2,然後單擊「添加1」,則會得到「21」,而不是預期的結果「3」。

我試圖谷歌一種方式來標記他們爲整數,但沒有運氣。

我的代碼是:

var CountComponent = React.createClass({ 

    resetCount: function() { 
     this.setState({ 
      count: '0' 
     }) 
    }, 

    addOne: function() { 
     this.setState({ 
      count: this.state.count + 1 
     }) 
    }, 

    getInitialState: function() { 
     return { 
      count: '0' 
     } 
    }, 

    render: function() { 
     return (
      <div> 
       <h1>Count {this.state.count}</h1> 
       <button onClick={this.addOne}>Add 1</button> 
       <button onClick={this.resetCount}>Reset</button> 
      </div> 
     ) 
    } 
}); 

ReactDOM.render(
    <CountComponent />, 
    document.getElementById('app') 
); 

會有人知道我已經錯在這裏?

奇怪的是,我確實找到了一個非常相似的例子,但它似乎工作https://codepen.io/ajcbrown820/pen/eZdWaj。我看不出與我的不同之處。

回答

2

因爲最初您將count的值定義爲字符串不是整數。當使用字符串+時,它將連接值。

使用此:

getInitialState: function() { 
    return { 
     count: 0 
    } 
}, 

resetCount: function() { 
    this.setState({ 
     count: 0 
    }) 
}, 

檢查這個片段:

let count = '0'; 
 

 
count = count + 1; 
 

 
console.log('count = ', count);

2

應使用數字而不是字符串!

添加字符串到數字,則將導致串聯它們,但增加的數字給對方,將導致增加的數量

getInitialState: function() { 
     return { 
      count: 0 
     } 
    }, 
    resetCount: function() { 
     this.setState({ 
      count: 0 
     }) 
    }, 

你也可以做到這一點,但它不是在這個例子中,更好的解決方案:

addOne: function() { 
     this.setState({ 
      count: +this.state.count + 1 
     }) 
    }, 

的+之前this.state.count將變成一個數加1而它之前。

0

你的號碼似乎是一個字符串!

嘗試在你的榜樣與0更換'0',並給它一個鏡頭:)

0

你的計數狀態被視爲一個字符串,因爲它是。嘗試將您的狀態設置爲0而不是「0」。

0

您已將getInitialStateresetCount成員中的字符串定義爲字符串。嘗試在上述函數中初始化count爲count:0(without apos);)

0

試試這個,刪除單引號爲0.引號將它視爲一個字符串,而不是一個整數。

resetCount: function() { 
    this.setState({ 
     count: 0 
    }) 
}, 

addOne: function() { 
    this.setState({ 
     count: this.state.count + 1 
    }) 
}, 

getInitialState: function() { 
    return { 
     count: 0 
    } 
}, 
0

您正試圖向字符串添加數字。所以這個數字也將被視爲字符串。

count: '0' 

應該

count: 0 

然後,它會正常工作。

0

試試,下面更正你的代碼。

var CountComponent = React.createClass({ 

    resetCount: function() { 
     this.setState({ 
      count: 0 
     }) 
    }, 

    addOne: function() { 
     this.setState({ 
      count: this.state.count + 1 
     }) 
    }, 

    getInitialState: function() { 
     return { 
      count: 0 
     } 
    }, 

    render: function() { 
     return (
      <div> 
       <h1>Count {this.state.count}</h1> 
       <button onClick={this.addOne}>Add 1</button> 
       <button onClick={this.resetCount}>Reset</button> 
      </div> 
     ) 
    } 
}); 

React.render(
    <CountComponent />, 
    document.getElementById('app') 
);