【问题标题】:Why am i getting undefined when accessing a closure variable in ReactJS为什么在 ReactJS 中访问闭包变量时我会变得未定义
【发布时间】:2023-03-10 17:44:01
【问题描述】:
我正在尝试在 ReactJS 中创建一个闭包。在 componentDidMount 方法中,我正在创建一个 http 请求,当请求完成时,我想访问 self 变量,但我无法访问。它是未定义的。有没有办法访问 self 变量?
componentDidMount() {
var self = this;
fetch('http://localhost:3000/test')
.then((response) => {
console.log(self); // undefined
})}
【问题讨论】:
标签:
javascript
reactjs
closures
【解决方案1】:
当我执行以下操作时,我得到了这个工作:
componentDidMount() {
var self = this;
const newfetch = fetch;
newfetch('http://localhost:3000/test')
.then((response) => {
console.log(self); // undefined
})}
【解决方案2】:
这似乎没有必要,因为箭头函数this 指的是词法范围。
const person = {
name: 'Bill',
likes: ['cake', 'mars', 'chickens'],
printLikes() {
this.likes.forEach((like) => {
console.log(this.name + " likes " + like);
});
}
};
// => Bill likes cake
// => Bill likes mars
// => Bill likes chickens