javascript - 为什么在 ReactJS 中访问闭包变量时我会变得未定义
问题描述
我正在尝试在 ReactJS 中创建一个闭包。在 componentDidMount 方法中,我正在创建一个 http 请求,当请求完成时,我想访问 self 变量,但我无法访问。它是未定义的。反正有没有访问 self 变量?
componentDidMount() {
var self = this;
fetch('http://localhost:3000/test')
.then((response) => {
console.log(self); // undefined
})}
解决方案
当我执行以下操作时,我得到了这个工作:
componentDidMount() {
var self = this;
const newfetch = fetch;
newfetch('http://localhost:3000/test')
.then((response) => {
console.log(self); // undefined
})}
推荐阅读
- javascript - 如何在不触发打印对话框的情况下执行 SSRS URL 操作?
- python - 问题透视数据框
- react-native - 无法提交表单 formik 和 react-native-elements
- ios - SwiftUI:显示重复按钮且未触发操作的催化剂警报
- c# - 图片框位置不会改变
- typescript - 打字稿从用户输入创建新类型
- docker - 错误:服务“mysql”构建失败:清单列表条目中没有 linux/arm/v7 的匹配清单
- c - 如何使用指针将从 Pthread 返回的多个数组存储在另一个数组中
- raku - Cro运行抛出连接被对等方重置
- java - google-drive-api - 使用我的帐户管理员更新文件