【发布时间】:2019-09-17 17:23:05
【问题描述】:
我有以下问题 - 我无法从我的状态读取值,我收到错误:
无法读取未定义的属性“状态”
我的类组件有一个状态:
class SideNav extends Component {
state = {
brand: 'Thule'
}
handleToggle = () => this.setState({open: !this.state.open});
handleBrand = (evt) => {
this.setState({brand: evt.target.value});
console.log(this.state.brand); --> WORKS HERE!!!
}
searchProducts() {
console.log(this.state.brand); --> ERROR: cannot read 'state' property of undefined
}
render() {
return (
<div className={classes.sideNav}>
<Button variant={"outlined"} onClick={this.handleToggle} className={classes.sideNavBtn}>Search</Button>
<Drawer
className={classes.drawer}
containerStyle={{top: 55}}
docked={false}
width={200}
open={this.state.open}
onRequestChange={open => this.setState({open})}
>
<AppBar title="Search"/>
<form noValidate autoComplete="off" onSubmit={this.searchProducts}>
<TextField
id="brand"
label="Brand"
margin="normal"
onChange={this.handleBrand}
/>
<Button variant="contained" color="primary" onClick={this.searchProducts}>
Search
</Button>
</form>
</Drawer>
</div>
);
}
}
export default SideNav;
我想知道为什么我能够在以下位置读取我的 this.state.bran 值:
handleBrand = (evt) => {
this.setState({brand: evt.target.value});
console.log(this.state.brand);
}
但不在
searchProducts() {
console.log(this.state.brand);
}
我不明白这个案子。
【问题讨论】:
标签: javascript reactjs react-state