javascript - vue和react中的功能相同,但在react中不起作用
问题描述
我在 React/Vue 中执行相同的登录功能。它在 VueJS 上运行良好,但是当我在 ReactJS 中使用时它不起作用。
Vue工作正常:
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
if (response.status == "200") {
this.getUsers();
console.log(response);
this.$router.push("intermediorotas");
this.showLogin = false;
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 2000);
}
},
},
反应不起作用:
EnvioLogin = async () => {
try {
const response = await axios.post("api/auth/login", { email: this.state.email, password: this.state.password });
localStorage.setItem("token", response.data.token);
if (response.status === "200") {
this.getUsers();
console.log(response);
this.props.history.push("/app");
}
} catch (error) {
this.setState({ error: "User or Password wrong!" });
setTimeout(() => {
this.setState({ error: "" });
}, 2000);
}
};
我在 try{} 中都使用了 console.log 并且在这两种情况下两个变量(电子邮件/密码)都到达那里,并且在浏览器中没有出现错误。我认为问题出在
const response = await axios.post("api/auth/login", { email: this.state.email, password: this.state.password });
localStorage.setItem("token", response.data.token);
获取用户Vue:
methods: {
async getUsers() {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
},
getUsers 反应:
componentDidMount() {
this.getUsers()
}
getUsers = async () => {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
};
解决方案
在 jsthis
中,普通函数和箭头函数的行为不同。而且严格模式和非严格模式也有区别。
特别是,箭头函数不绑定到调用者的上下文。如果您使用的函数/库实际上取决于此行为,则会产生一些非常晦涩的错误。
您的 2 个函数的定义不同。第一个是普通函数,第二个是箭头函数。他们也参考了这一点。
您可以检查this
first 的使用情况。但是如果没有更多上下文/可重现的代码,就很难理解这个问题。
参见:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
推荐阅读
- sql - Oracle:根据不同列的值选择不同的列
- python - 如何导出然后导入密钥进行解密?
- azure - aks:尝试创建负载均衡器时出现未经授权的错误
- r - 如何在ggplot2的箱线图中添加每组的观察次数和中位数
- linux - 按范围查找编号文件 - 模式匹配 - 从命令行
- html - 使用 IOS 14 Safari/Chrome 在 IOS 14 Safari/Chrome 上加载 WebP 图像
- javascript - 如何使用 SH 文件在 Linux 中运行 JavaScript 文件
- android - 如何在 Kotlin Android 的 recyclerView 中以相反的顺序显示从 Firestore 检索到的数据?
- amazon-web-services - 用于秘密管理评估的 Convox 环境
- laravel - Laravel 模型没有从表中获得任何价值