[英]React state component - Cannot read property 'state' of undefined
I have the following problem - I can't read value from my state, I get the error: 我有以下问题-无法从状态读取值,但出现错误:
Cannot read property 'state' of undefined
无法读取未定义的属性“状态”
My class component with a state: 我的类组件状态为:
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;
I wonder WHY I'm able to read my this.state.bran value in: 我想知道为什么我能够在以下位置读取我的this.state.bran值:
handleBrand = (evt) => {
this.setState({brand: evt.target.value});
console.log(this.state.brand);
}
but NOT in 但不在
searchProducts() {
console.log(this.state.brand);
}
I don't understand this case. 我不明白这种情况。
searchProducts
is a class method
either bind
it in constructor
or use arrow functions
(like in handleBrand
). searchProducts
是一个class method
可以在constructor
arrow functions
bind
它,也可以使用arrow functions
(例如handleBrand
)。 Currently your accessing the wrong value for this
当前,您
this
了错误的值
searchProducts = () =>{}
Using bind
使用
bind
constructor(){
this.searchProducts = this.searchProducts.bind(this)
}
Arrow functions have lexical this
. 箭头函数具有
lexical this
。 By using this
inside a class method you are accessing the local scope
of searchProducts
not the Component
's instance 通过在类方法中使用
this
方法,您正在访问searchProducts
的本地scope
, searchProducts
不是Component
的实例
this
works in confusing ways in JavaScript. this
在JavaScript中以令人困惑的方式工作。 It's not working as intended in searchProduct()
because you're passing it as a prop to a child component. 它没有按
searchProduct()
预期工作,因为您将其作为道具传递给子组件。 In your constructor you should bind it to the instance like this: 在构造函数中,应将其绑定到实例,如下所示:
constructor(props) {
super(props);
this.searchProducts = this.searchProducts.bind(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.