【问题标题】:Why is 'this' itself undefined in function scope为什么'this'本身在函数范围内未定义
【发布时间】:2018-06-19 09:53:58
【问题描述】:

我有以下代码:

class App extends Component {

  constructor(){
    super()
    //this.buttonOneClick = this.buttonOneClick.bind(this);
  }

  buttonOneClick() {
    const { setTestData } = this.props;

    setTestData("test");
  }

  render() {
    const { testData } = this.props;
    return (
      <div className="App">
        <h1>Test App</h1>
        <div>{testData}</div>
        <button onClick={this.buttonOneClick}>Test</button>
      </div>
    );
  }
}

组件 App 使用 react-redux 的 connect 方法导出,以将 setTestData-function 映射到 props(这是 setTestData 的来源)。

当我设置 buttonOneClick() 处理程序而不将组件上下文绑定到它时(请参阅 constructor() 中我的代码中注释掉的行)我收到以下错误:

无法读取未定义的属性“道具”

我知道不会定义 props,因为处理程序是在不了解 props 的全局上下文中执行的,但我如何理解错误,这意味着 this 本身没有定义,这没有意义对我来说。为什么会这样? this 不应该总是在任何执行上下文中定义吗?

提前致谢

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这不应该总是在任何执行上下文中定义吗?

    没有。

    在严格模式下没有隐含的this 值。

    "use strict";
    
    function example() {
        alert(this);
    }
    
    example();

    【讨论】:

    • 恕我直言,值得一提的是类主体强制执行严格模式。
    • 很高兴知道。我现在将阅读有关严格模式的更多信息(我是否理解正确,只要它引用全局上下文,'this' 仅在严格模式下是未定义的?)
    【解决方案2】:

    我们收到一个错误,因为在 onClick 调用我们的 buttonOneClick() 函数时没有定义 this

    通常,您可以通过将 this 绑定到 buttonOneClick 函数来解决此问题,使其始终保持不变。所以我们必须在构造函数中绑定它。

    this.buttonOneClick = this.buttonOneClick.bind(this);
    

    如果您不想使用绑定,则可能的解决方法是使用 es2015 javascript 箭头函数

    buttonOneClick = () => console.log(this.props);
    

    箭头函数没有自己的 this,因此它会使用 this 脱离其上下文,即我们的组件。这称为词法作用域

    【讨论】:

    • 另外,问题不在于如何取消注释代码行,而在于this 如何得到undefined
    • 更新了答案@YuryTarabanko
    • @B001ᛦ 我误解了这个问题。我已经更新了我的答案
    猜你喜欢
    • 2014-02-25
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    相关资源
    最近更新 更多