javascript - 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 承诺,其中承诺值是“未定义”。如何进行异步调用并解决此问题?
解决方案
componentDidUpdate
被包裹在if (this.state.check)
. 您粘贴的代码中没有任何内容设置this.state.check
为 true。设置this.state.check: true
。
推荐阅读
- coq - 为什么基于微积分的语言如此多地使用 Setoid?
- mysql - 如何在 MySQL 中找到不同组的列的聚合总和的差异?
- python - 装饰器函数来包装一个函数?
- android - 如何使用 RxAndroidBle 调用多个 setupIndication
- vue.js - NuxtJS中如何为publicPath、outputDir、indexPath配置不同的路径
- ios - SwiftUI - 输入文本时防止 TextField 扩展
- c++ - 将 char** 转换为 int C++
- rust - 变量的所有权如何在迭代之间起作用?
- php - 限制机器中的索引文件
- typescript - 如何在 Nestjs 的 service.spec 文件中模拟 gmail 以及如何测试它?