2017-04-27 70 views
0

嘗試了我的第一次反應,但卡住了,想要做多重綁定。狀態未定義錯誤使用setState

class HelloWorldComponent extends React.Component { 
    constructor(props){ 
    super(props); 

    this.state = { 
     price 
    } 
    } 

    render() { 
    return (
     <div> 
     <input type="text" onChange={e => this.setState({price: e.target.value})} placeholder="main price"/> 
     <input type="text" placeholder="custom price"/> 
     </div> 
    ); 
    } 
} 

我上面的代碼有什麼問題?價格沒有定義?我已經聲明

this.state = { 
    price 
} 

回答

0

原因是,當你寫:

this.state = { price } 

這將被視爲:

this.state = { price : price } 

而且它引發錯誤,因爲沒有定義超值價

爲了解決這個問題,無論是確定的價格或將值賦給關鍵價位是這樣的:

this.state = { price : '' }; 

檢查這個片段:

str = 'a'; 
 

 
obj = {str}; 
 

 
console.log(obj);

+0

正確。我也在檢查一樣。我的答案在這裏是錯誤的。 – Ved

相關問題