React 类组件中意外的关键字"this"



在尝试使用Redux传奇更新react状态时,我收到一个错误意外关键字"this"。有人能向我解释以下代码的问题以及如何纠正吗?

class Welcome extends React.Component {

removeCartItems = (cartItems) => {
cartItems.map((product, index) => ({
this.props.dispatch(removeItem(product)) // Getting error Unexpected keyword 'this'
}));
};
render() {
this.removeCartItems(cartItems)
return (<h1>Remove product from cart</h1>);
}
}

您需要删除括号,否则JS会将其解释为您试图从箭头函数返回对象。

() => { this. ... }

() => ({})

在您的情况下,它将以以下方式显示。

cartItems.map((product, index) => {
this.props.dispatch(removeItem(product));
});

最新更新