无法设置未定义的 属性 'x'
Cannot set property 'x' of undefined
我想在商店设置变量。
这是我的商店
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 获取方法中遇到此错误;
Cannot set property 'categories' of undefined
改用箭头函数:
@action getCategories = () =>{
fetch('http://localhost:3000/categories')
.then((resp) => resp.json())
.then((resp2) => {
this.categories=resp2;
});
}`
函数关键字将 "this" 关键字绑定到自身,但箭头函数将其绑定到上下文
我想在商店设置变量。 这是我的商店
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 获取方法中遇到此错误;
Cannot set property 'categories' of undefined
改用箭头函数:
@action getCategories = () =>{
fetch('http://localhost:3000/categories')
.then((resp) => resp.json())
.then((resp2) => {
this.categories=resp2;
});
}`
函数关键字将 "this" 关键字绑定到自身,但箭头函数将其绑定到上下文