vue 和 react 中的功能相同,但在 react 中不起作用 [英] Same function in vue and react but doesnt work in react
问题描述
我在 React/Vue 中执行相同的登录功能.它在 VueJS 上运行良好,但当我在 ReactJS 中使用时它不起作用.
Im doing the same login function in React/Vue. It works fine on VueJS but when i use in ReactJS it doesnt work.
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);
}
},
},
React 不起作用:
React doesnt working:
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 在这两种情况下都到达那里并且在浏览器中没有出现错误..我认为问题出在
I used console.log in both try{} and both variables(email/password) are getting there in both cases and in the browser no errors appears.. I think the problem is in the
const response = await axios.post("api/auth/login", { email: this.state.email, password: this.state.password });
localStorage.setItem("token", response.data.token);
getUsers 视图:
getUsers vue:
methods: {
async getUsers() {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
},
getUsers 反应:
getUsers React:
componentDidMount() {
this.getUsers()
}
getUsers = async () => {
const response = await axios.get("api/alunos", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
});
console.log(response);
};
推荐答案
在 js 中,this
在普通函数和箭头函数中表现不同.严格模式和非严格模式也有区别.
In js, this
behaves differently in ordinary function and arrow function. And there is also difference between strict mode and non-strict mode.
特别是,箭头函数不绑定到调用者的上下文.如果你的函数/你使用的库实际上依赖于这种行为,它会产生一些非常模糊的错误.
Specially, arrow function don't bind to the caller's context. If your function/the lib you use actually depends on this behaviour, it would create some very obscure bug.
您的 2 个函数的定义不同.第一个是普通函数,第二个是箭头函数.他们也参考了这个.
Your 2 functions are defined differently. The first one is ordinary function and the second one is arrow function. and they also reference this.
您可以先查看this
的用法.但是如果没有更多上下文/可重现的代码,就很难理解问题.
You could check on the usage of this
first. But it will be hard to understand the problem without more context/reproducible code.
见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
这篇关于vue 和 react 中的功能相同,但在 react 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!