javascript - 外部 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 始终未定义。我如何将它与特定组件绑定?
解决方案
我建议不要尝试在您的外部 request() 函数中做任何反应。
相反,现在您的 request() 函数正在返回一些东西,因此无论在哪里调用它(最有可能在反应组件中),您都可以将 .then() 链接到它。
因此,在使用它的反应组件中:
import { get } from '...'
ReactComponent extends Component {
classMethodToMakeRequest() {
get('someurl.com').then(() => this.props.history.push('/push/route'))
}
}
您只能this.props
从反应组件中访问。
推荐阅读
- c# - 循环遍历 C# 中的字典
- pandas - 我的 .loc 有多个条件一直在运行...帮我降落飞机
- swift - 如何防止 Sprite 节点相互推挤?
- ruby-on-rails - 有没有办法让 smart_listing 立即跳转到最后一页?
- php - 如何在 php 中将 tinyint 值更新为 1 而不是变为 NULL
- apache-spark - 当数据大小远大于 Cluster 中的可用内存时,Spark 如何进行内存计算
- javascript - 我无法理解特定的“this”绑定
- sparql - 使用命令行在jena tdb中读取多个查询?
- sql-server - 如何使用 T-SQL 中两个不同表中的值调用 Levenshtien 函数
- java - 设置和显示名称和电子邮件 Java 对象类