【问题标题】:How to read props inside a socket.io callback?如何在 socket.io 回调中读取道具?
【发布时间】:2017-05-08 14:25:59
【问题描述】:

当我尝试在套接字回调函数中读取我的道具时,它会抛出一个错误:

componentWillMount(){

    console.log(this.props.username); // works
    this.props.socket.on('question', function(){
      console.log(this.props.username); //prints Cannot read property 'username' of undefined
      }
    });
  }

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs socket.io


    【解决方案1】:

    问题是function() 调用改变了上下文并且this 不再指向组件的实例,因此this.propsundefined。您可以使用arrow function,它将this 作为组件的实例。

    箭头函数不会创建自己的 this 上下文,因此 this 具有其封闭上下文的原始含义。

    componentWillMount() {
      this.props.socket.on('question', () => { // arrow function
        console.log(this.props.username); 
      });
    }
    

    【讨论】:

      【解决方案2】:

      绑定套接字函数的上下文,这样你就可以从 React 组件的上下文中访问 props,否则 socket.on 函数中的 this 将引用它自己的上下文而不是 React 组件

      this.props.socket.on('question', function(){
        console.log(this.props.username); 
        }.bind(this)
      });
      

      this.props.socket.on('question', () => {
        console.log(this.props.username); 
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-12
        • 1970-01-01
        • 1970-01-01
        • 2016-01-06
        • 2016-05-22
        • 2023-03-20
        相关资源
        最近更新 更多