【问题标题】:Cannot Read Properties Of Undefined Reading handleCategory无法读取未定义读取句柄类别的属性
【发布时间】:2021-12-30 21:41:17
【问题描述】:

我正在尝试处理简单的单击操作,我正在使用基于类的组件,并且我根据文档绑定了该方法并使用了“this”,但发生错误说无法读取 handleCategory 的属性,这是我的代码

import React from 'react';
import classes from '../css/Landing.module.css';
import mainClasses from '../../MainCss/MainClasses.module.css';
import { LOAD_CATEGORIES } from '../../graphql/queries';
export default class Landing extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            categories: [],
            loading: true,
            category: null,
        };
        this.handleCategory = this.handleCategory.bind(this);
    }

    async componentDidMount() {
        const { client } = this.props;
        const { data } = await client.query({ query: LOAD_CATEGORIES });
        const { categories } = data;
        this.setState((prevState) => ({ ...prevState, categories: categories, loading: false, category: categories[0]?.name }));
    }

    handleCategory(e) {
        this.setState((prevState) => ({ ...prevState, category: e.target.value }));
    }

    renderCategory(category) {
        return (
            <option onClick={this.handleCategory} key={category.name} value={category.name}>
                {category.name}
            </option>
        );
    }

    render() {
        return (
            <div className={`${classes.root} ${mainClasses.container} ${mainClasses.column}`}>
                <div className={`${mainClasses.container} ${mainClasses.row}`}>
                    <label className={classes.categorylabel}>Choose Category</label>
                    {this.state.loading ? 'loading' : <select className={classes.categorymenu}>{this.state.categories.map(this.renderCategory)}</select>}
                </div>
                <div>{this.state.category}</div>
            </div>
        );
    }
}

【问题讨论】:

    标签: javascript reactjs event-handling dom-events


    【解决方案1】:

    handleCategory 方法转换为箭头函数:

    handleCategory = (e) => {
        this.setState((prevState) => ({ ...prevState, category: e.target.value }));
    }
    

    通过这样做,您可以从构造函数中删除显式绑定。
    更多信息请阅读here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2018-04-12
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多