繁体   English   中英

在 vue 和反应中相同的 function 但在反应中不起作用

[英]Same function in vue and react but doesnt work in react

我在 React/Vue 中做同样的登录 function。 它在 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);
  };

在 js 中, this在普通 function 和箭头 function 中表现不同。 而且严格模式和非严格模式也有区别。

特别是,箭头 function 不绑定到调用者的上下文。 如果您使用的函数/库实际上取决于此行为,则会产生一些非常晦涩的错误。

您的 2 个函数的定义不同。 第一个是普通的function,第二个是箭头function。 他们也参考了这一点。

你可以先检查一下this的用法。 但是如果没有更多上下文/可重现的代码,就很难理解这个问题。

参见: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM