首页 > 解决方案 > react js中的状态变量有问题。无法将变量的值更新为 true

问题描述

import getAuthentication from './getAuthentication';

 class Home extends React. Component {
      constructor() {
        super();
        //this.authentication = false;
        this.state = {
          username: '',
          password: '',
          check:false,
          authentication:false
        };
        this.err = '';
      }



      componentDidUpdate() {
        console.log (this.state.authentication);
        console.log(this.state.authentication == true);

    if (this.state.check)
    {
        const promiseAuthentication = getAuthentication(
          this.state.username,
          this.state.password,
        );
        promiseAuthentication
          .then(response => {
            console.log (response.data.Success);
            console.log(response.data.Success == true);
            this.setState({check :false, authentication:response.data.Success});

          })
          .catch(error => {
            // console.log(error);
            this.err = error;
          });

      }

      if (this.state.authentication == true) {
        event.preventDefault();
        history.push('/overview');
       } 

      }

      assignUsername = event => {
        this.setState({ username: event.target.value });
      };

      assignPassword = event => {
        this.setState({ password: event.target.value });
      };

      handleSubmit = () => {
        this.setState({ check:true });
      };
==============================================================

getAuthentication.js

import axios from 'axios';

function getAuthentication(username, password) {
  const authenticationConfig = {
    Email: username,
    Password: password,
  };
  return axios.post(
    'http://localhost:5002/login/confirmation',
    authenticationConfig,
  );
}

export default getAuthentication;

在上面的代码中,我this.state.Authentication没有更新到true

我正在尝试在 axios promise 中更新它的值。

有人可以告诉我有什么问题吗?我的意思是我已经尝试了一切,但我无法继续。

如何更改身份验证对象的状态并切换新窗口?

我有第二个文件返回 axios 承诺,其中承诺值是“未定义”。如何进行异步调用并解决此问题?

标签: javascriptreactjsaxioses6-promise

解决方案


componentDidUpdate被包裹在if (this.state.check). 您粘贴的代码中没有任何内容设置this.state.check为 true。设置this.state.check: true


推荐阅读