首页 > 解决方案 > 为什么在 ReactJS 中访问闭包变量时我会变得未定义

问题描述

我正在尝试在 ReactJS 中创建一个闭包。在 componentDidMount 方法中,我正在创建一个 http 请求,当请求完成时,我想访问 self 变量,但我无法访问。它是未定义的。反正有没有访问 self 变量?

  componentDidMount() {
    var self = this;
    fetch('http://localhost:3000/test')
    .then((response) => {
      console.log(self); // undefined
    })}

标签: javascriptreactjsclosures

解决方案


当我执行以下操作时,我得到了这个工作:

  componentDidMount() {
    var self = this;
    const newfetch = fetch;
    newfetch('http://localhost:3000/test')
    .then((response) => {
      console.log(self); // undefined
    })}

推荐阅读