无法设置未定义的属性'x'

问题描述 投票:1回答:1

我想在商店设置变量。这是我的商店

class storeCategory{

    @observable categories =[];

    @action getCategories = () =>{
        fetch('http://localhost:3000/categories')
        .then((resp) => resp.json())
        .then(function(resp2){
            this.categories=resp2;
        });
    }


}

这是我的组件

@inject('sCategory')
@observer
class Category extends React.Component{

    componentDidMount=()=>{
       this.props.sCategory.getCategories();
    }

    render(){
        const {sCategory} = this.props;
        return (
            <ListGroup>
                {this.props.sCategory.categories.map((cat, index) => {
                            return (
                                <ListGroupItem key={cat.id}>{cat.categoryName}</ListGroupItem>
                            )
                        })}
            </ListGroup>
          );
    }
}

我添加到sCategory到提供者位于index.js的位置

在获取方法中的this.categories = resp2处出现此错误;

无法设置未定义的属性'类别'

javascript reactjs mobx mobx-react
1个回答
0
投票

改为使用箭头功能:

@action getCategories = () =>{
    fetch('http://localhost:3000/categories')
    .then((resp) => resp.json())
    .then((resp2) => {
        this.categories=resp2;
    });
}`
© www.soinside.com 2019 - 2024. All rights reserved.