【发布时间】:2018-03-31 22:46:22
【问题描述】:
我正在尝试在箭头函数的函数内使用This。如何在我的函数中使用setState?
showDeleteConfirm = commentId => {
const { deleteComment } = this.props;
const { comments } = this.state;
// this exist
confirm({
title: 'Are you sure delete this?',
okText: 'Yes',
okType: 'danger',
cancelText: 'No',
onOk() {
// this is undefined
deleteComment(commentId);
const targetPosition = _.findIndex(comments, item => {
return item._id === commentId;
});
if (targetPosition !== -1) {
// this is undefined
console.log(this.state.comments);
this.setState(prevState => ({
comments: [
...prevState.comments.slice(0, targetPosition),
...prevState.comments.slice(targetPosition + 1)
]
}));
}
},
onCancel() {
console.log('Cancel');
}
});
};
【问题讨论】:
-
this未在箭头函数上定义。它直接进入它的父范围。
标签: javascript reactjs arrow-functions