【问题标题】:React state component - Cannot read property 'state' of undefined反应状态组件 - 无法读取未定义的属性“状态”
【发布时间】: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


【解决方案1】:

searchProductsclass method 或者 bindconstructor 中或使用 arrow functions (如在 handleBrand 中)。目前您访问的 this 值错误

searchProducts = () =>{}

使用bind

constructor(){
    this.searchProducts = this.searchProducts.bind(this)
}

箭头函数有lexical this。通过在类方法中使用this,您访问的是searchProducts 的本地scope,而不是Component 的实例

【讨论】:

  • AAAAh 我是如此接近......工作!谢谢!但是为什么我需要这样的表格呢?
  • 更新了答案
【解决方案2】:

this 在 JavaScript 中工作于 confusing ways。它没有按searchProduct() 中的预期工作,因为您将它作为道具传递给子组件。在您的构造函数中,您应该像这样将它绑定到实例:

constructor(props) {
  super(props);
  this.searchProducts = this.searchProducts.bind(this);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2019-07-25
    • 2020-11-05
    • 2021-07-07
    相关资源
    最近更新 更多