【问题标题】:can't setState in a function inside a arrow function on React无法在 React 的箭头函数内的函数中设置状态
【发布时间】: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


【解决方案1】:

你可以在箭头函数中得到this 就好了(method = () => {}),尽管鼓励在类中使用方法(method() {})。您面临的问题不在于使用箭头函数,而在于您在何处以及如何调用它。代码的第一部分有效,因为您立即调用它。而onOK 和onCancel 在稍后的时间,更重要的是在showDeleteConfirm 的上下文之外,在那里定义了onOK。当然onOK 会使用它自己的this,而不是showDeleteConfirm'sthis。解决方法如下:

showDeleteConfirm = commentId => {
    const { deleteComment } = this.props;
    const { comments } = this.state;

    confirm({
        title: 'Are you sure delete this?',
        okText: 'Yes',
        okType: 'danger',
        cancelText: 'No',
        onOk: this.onDeleteConfirm.bind(this, commentId),
        onCancel: this.onDeleteCancel.bind(this)
    });
};

onDeleteConfirm = (commentId) => {
    const { comments } = this.state;
    const targetPosition = comments.findIndex(item => item._id === commentId);

    this.props.deleteComment(commentId);

    if (targetPosition !== -1) {
        this.setState(prevState => ({
            comments: [
                ...prevState.comments.slice(0, targetPosition),
                ...prevState.comments.slice(targetPosition + 1)
            ]
        }));
    }
}

onDeleteCancel = () => {}

我们将this 绑定到onDeleteConfirm 和onDeleteCancel,因此当它们最终执行时,它们会正确地得到它们。您可以在此处阅读大量绑定:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

【讨论】:

    【解决方案2】:

    你不能,箭头函数中的this 总是与其周围块中的this 相同。只需使用常规函数即可。

    const showDeleteConfirm = function(commentId) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2021-02-13
      • 2021-01-02
      相关资源
      最近更新 更多