handleSelectChange console.log(this.state.selectValue); 打印值但时addProduct 已执行的抛出错误 this.state.selectValue 未定义
无法阅读属性' selectValue'未定义的
handleSelectChange(e){
console.log(e.target.value);
this.setState({selectValue: e.target.value});
console.log(this.state.selectValue); //here ok
}
addProduct(e){
console.log(this.state.selectValue); //here error
this.setState({products: [ ...this.state.products, this.state.selectValue]});
}
<FormGroup>
<Input type="select" value={this.state.selectValue} onChange={this.handleSelectChange.bind(this)} name="select" id="exampleSelect">
<option value="Product 1">Product 1</option>
<option value="Product 2">Product 2</option>
<option value="Product 3">Product 3</option>
<option value="Product 4">Product 4</option>
<option value="Product 5">Product 5</option>
</Input>
<Input placeholder="Quantity" type="number" name="posotita" id="posotita" />
<Button color="primary" onClick={this.addProduct}>Add</Button>
</FormGroup>
答案 0 :(得分:1)
this.state.selectValue
未定义可能意味着此现在指向的不是您所在州的组件。尝试绑定此方法,如:
<Button color="primary" onClick={this.addProduct.bind(this)}>Add</Button>