2017-04-27 69 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

相关问题