<分区>
我正在使用 React,在我的 componentDidMount() {}
中我正在调用一个导入的函数,并想在其中访问 this.setState
。
在 componentDidMount
中,当我 console.log(this)
时,我按预期获得了组件。
但是如果我运行 myFunction.call(this)
,myFunction 中的 console.log(this)
将返回 undefined
。
知道为什么 this
没有被正确传递吗?
edit1:添加代码。
组件:
class Navbar extends React.Component {
componentDidMount() {
myFunction.call();
}
}
我的函数.js:
export const myFunction = () => {
console.log('this:', this);
}
控制台输出:
this: undefined
edit2:有些人将其标记为“我可以绑定(bind)箭头函数”的副本,但 myFunction 是一个箭头函数,即使我直接调用它而不是使用 .call() 也会产生相同的结果:this
未定义。