2016-12-01 18 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值时具有其自己的特定行为。

相关问题