首页 > 解决方案 > 外部 fetch 函数中的 this.props 未定义

问题描述

我在我的项目中使用 React.js。我在外部提取功能中遇到了 this.props 的问题。这是我的代码

export default function request(method, url, body) {
  console.log(this); //undefined here
  if (method === "GET") {
    body = undefined;
  }
  return fetch(url, {
    method,
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      Authorization: "Bearer " + token
    },
    body
  }).then(res => {
    console.log(this); //undefined here
    if (res.status === 401) {
      this.props.history.push("/login");
      return Promise.reject("Unauthorized.");
    } else {
      return res;
    }
  });
}

export const get = url => request("GET", url);
export const post = (url, body) => request("POST", url, body);
export const put = (url, body) => request("PUT", url, body);
export const del = (url, body) => request("DELETE", url, body);

如果 res.status ===401。我希望我的程序可以跳回登录。但是,我的函数中的 this.props 始终未定义。我如何将它与特定组件绑定?

标签: javascriptreactjsfrontendfetch

解决方案


我建议不要尝试在您的外部 request() 函数中做任何反应。

相反,现在您的 request() 函数正在返回一些东西,因此无论在哪里调用它(最有可能在反应组件中),您都可以将 .then() 链接到它。

因此,在使用它的反应组件中:

import { get } from '...'

ReactComponent extends Component {

  classMethodToMakeRequest() {
    get('someurl.com').then(() => this.props.history.push('/push/route'))
  }

}

您只能this.props从反应组件中访问。


推荐阅读