【问题标题】:Error of 'this' when trying to setState in Modal尝试在 Modal 中设置状态时出现“this”错误
【发布时间】:2017-11-07 22:33:41
【问题描述】:

我正在尝试执行删除确认模式。

  handleDelete (){
console.log('handleDelete')
const { something} = this.state
confirm({
  title: 'Are you sure you want delete?',
  content: 'Press Ok to continue, Cancel to return',
  onOk () {
    console.log('onOK')
    this.setState({ something: [] })
  }
})

}

按下删除按钮后,将显示确认模式。如果用户按确定,那么它将删除确认模式后面的内容。

但无法删除。我收到错误消息:

TypeError: this is undefined

在这一行:

this.setState({ something: [] })

是我试图在未安装的组件上设置状态吗? 那么正确的做法是什么呢?

【问题讨论】:

  • 在确认代码之前尝试 var _this = this,并使用 _this 代替 this
  • 我已经更新了我的问题 Jaromanda X。错误来自 this.setState({ something: [] }) 行。
  • 是的,我怀疑是这样的
  • 你应该使用箭头函数来保存this
  • 在 javascript 中,@SLaks,这是一个箭头函数,在 javascript 文档中查找“lambda”不会引导您使用箭头函数 - 它需要将行 onOk () { 更改为 onOk: () => {

标签: javascript html reactjs react-native modal-dialog


【解决方案1】:

你可以使用箭头功能,它有效。

onOk: () => { console.log('onOK') this.setState({ something: [] }) }

【讨论】:

    【解决方案2】:

    您尚未发布组件的代码,但如果您使用的是 class 组件,那么在 class 内声明的任何方法都应将 bindthis 对象硬绑定到 class 实例,因此您可以访问“存在”在此实例中的 state 对象。

    这通常在classconstructor中完成:

    constructor(props){
      super(props);
      this.handleDelete = this.handleDelete.bind(this);
    }
    

    另一种方法是使用ES6 arrow functions,它将使用this 关键字的词法上下文,这意味着,如果您的处理程序在class 中声明,则此方法的词法上下文是@987654333 @ 本身,因此 this 关键字将引用 class

    handleDelete = () => {
      // your code...
    }
    

    【讨论】:

    • onOk () { 是问题所在
    【解决方案3】:
    class Something extends React.Component {
    constructor(props) {
        super(props);
    
        this.handleDelete = this.handleDelete.bind(this);
    }
    
    handleDelete() {
        console.log('handleDelete');
        const { something } = this.state;
    
        confirm({
            title: 'Are you sure you want delete?',
            content: 'Press Ok to continue, Cancel to return',
            onOk: () => {
                console.log('onOK')
                this.setState({ something: [] })
            },
            onOkWithoutArrow: function(){
               this.setState({..});
            }.bind(this);
        });
    }
    
    render() {
        return <Component onClick={this.handleDelete} />;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2011-05-08
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多