2017-01-31 64 views
-2

我有以下反應頁,並使用計數器,當我得到遺漏的類型錯誤:無法讀取屬性「的setState」空的陣營

Uncaught TypeError: Cannot read property 'setState' of null 

。 它似乎有通過的setState

<!DOCTYPE html> 
<html> 

<head> 
    <title>counter</title> 
    <script src="https://unpkg.com/[email protected]/dist/react.js"></script> 
    <script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.0.0-beta.3/react-router.min.js"></script> 

<head> 


<body> 


    <div id="entry"></div> 

    <script type="text/babel"> 
     var destination = document.querySelector("#entry"); 



class Counter extends React.Component { 
    constructor() { 
     super(); 
     this.state = { value: 0}; 
    } 

    increment(){ 
    this.setState(function(prevState){ 
     value: prevState.value + 1 
    }); 
    }; 

    decrement(){ 
    this.setState(prevState => ({ 
     value: prevState.value - 1 
    })); 
    }; 

    render() { 
    return (
     <div> 
     {this.state.value} 
     <button onClick={this.increment}>+</button> 
     <button onClick={this.decrement}>-</button> 
     </div> 
    ) 
    } 
} 

ReactDOM.render(
    <div> 
     <Counter/> 
    </div>, 
    destination 
) 

     </script> 
    </body> 

</html> 

我只是改變increment一箇舊式的功能和沒有工作使用的this做。

+1

推薦閱讀http://blog.andrewray.me/ react-es6-autobinding-and-createclass/ –

+0

[Can not read property'setState'null] - React.js,Modal,Bootstrap](http://stackoverflow.com/questions/40694468/cannot-read-property -setstate-的空反應的JS-模態的自舉) – Pineda

回答

1

您必須將環境傳遞給ES6模式下的自定義函數。

有很多方法可以做到這一點,一個好的起點是這裏sitepoint article這裏。

作爲開始,改變你的構造函數 -

constructor() { 
     super(); 
     this.state = { value: 0}; 
     this.increment = this.increment.bind(this); 
     this.decrement = this.decrement.bind(this); 

    } 

你可以做同樣的onClick爲好,但恕我直言,這似乎更整潔

相關問題