2016-12-01 23 views
1

我想知道爲什麼,如果我修改此行{this.increaseQty.bind(this)}{this.increaseQty},控制檯會提示遺漏的類型錯誤:無法讀取的不確定代替遺漏的類型錯誤財產「的setState」:this.setState不是一個函數(...)?如果未設置綁定,則不應該將this作爲窗口對象?未設置綁定時,爲什麼`this`不是指窗口對象?

export default class CartItem extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      qty: props.initialQty, 
      total: 0 
     }; 
    } 
    componentWillMount() { 
     this.recalculateTotal(); 
    } 
    increaseQty() { 
     this.setState({qty: this.state.qty + 1}, this.recalculateTotal); 
    } 
    decreaseQty() { 
     let newQty = this.state.qty > 0 ? this.state.qty - 1 : 0; 
     this.setState({qty: newQty}, this.recalculateTotal); 
    } 
    recalculateTotal() { 
     this.setState({total: this.state.qty * this.props.price}); 
    } 
    render() { 
     return <article className="row large-4"> 
      <figure className="text-center"> 
       <p> 
        <img src={this.props.image}/> 
       </p> 
       <figcaption> 
        <h2>{this.props.title}</h2> 
       </figcaption> 
      </figure> 
      <p className="large-4 column"><strong>Quantity: {this.state.qty}</strong></p> 

      <p className="large-4 column"> 
       <button onClick={this.increaseQty.bind(this)} className="button success">+</button> 
       <button onClick={this.decreaseQty.bind(this)} className="button alert">-</button> 
      </p> 

      <p className="large-4 column"><strong>Price per item:</strong> ${this.props.price}</p> 

      <h3 className="large-12 column text-center"> 
       Total: ${this.state.total} 
      </h3> 

     </article>; 
    } 
} 
+0

在ES6中,默認情況下你處於嚴格模式,所以這將是'undefined'。 – Ben

回答

4

如果不調用函數的方法(和它不綁定,並且不使用電話或應用),那麼this函數內部的值將是undefined IF:

  • 你是在嚴格模式下
  • 你在ES2015(嚴格模式是默認的)

否則這將是全局對象。另外,請注意,某些主機對象(例如setTimeout)在定義例如調用回調時使用的this值時具有其自己的特定行爲。

相關問題