首页 > 解决方案 > 未捕获的类型错误:无法读取未定义的属性“enqueueSetState”

问题描述

我正在尝试使用参数调用此函数以映射 filterCategories,但出现此错误。

            interface FrontPageComponents {
                filterCategories: GetTheActivity[];
            }
        
            export class FrontPage extends React.Component<RouteComponentProps<{}>, FrontPageComponents> {
        
        constructor() {
                super();
                this.state = {filterCategories: []};
        
        }
            public sort(event: string) {   
            
                    
                     console.log(event);
                     return (
            
                         $.ajax({
                             type: "POST",
                             url: './Categ/GetFilterCategories',
                             dataType: 'json',
                             data: { _event: event },
                             success: (response) => {
                                 FrontPage.prototype.setState({                     //in this line the error
                                     filterCategories: response
                                 }) }
                         })
                         
                         );
                    
            
            
                } 
    
    public render() {
    return      <div>
    <Sorting />
    </div>;
    
    }   

}

在排序组件中,我这样调用函数:

FrontPage.prototype.sort(event.target.innerText);

标签: c#reactjstypescriptasp.net-core

解决方案


之所以this没有定义是因为如果this在ajax里面调用success方法this是指响应的范围。

尝试执行以下操作:const that = this;在 ajax 请求之上。然后在success方法中调用that.setState(...)。在这种情况下that指的是组件的当前实例。

我知道这是一个肮脏的修复,但它有效。


推荐阅读