当我尝试获取用于登录的 API 时,我陷入了某些显示 loading 的项目。我用
考虑下面的代码:
login(){
const { history } = this.props;
PostData('api/users/login', this.state)
.then ((result) => {
let responseJSON = result;
this.setState({
loaded: true
})
if(this.state.loaded === true){
if(responseJSON.success === true){
localStorage.setItem('loginEmail', this.state.loginEmail);
localStorage.setItem('id', responseJSON.user.id);
history.push('/Home') // when successfully login, it will go to Home Page
}else if(responseJSON.success === false){
alert("Wrong User Credential")
}}else if(this.state.loaded === false){
return(
<LinearProgress /> // for loading
)
}
}).catch((error) => {
console.log(error)
})
}
这是我的 this.state 构造函数
constructor (props){
super(props);
this.state ={
loginEmail: '',
loginPassword: '',
error: {},
loaded: false,
history: PropTypes.object.isRequired
}
this.login = this.login.bind(this);
this.onChange = this.onChange.bind(this);
}
我在登录功能中使用的加载方式是否错误?为什么加载错误时无法显示线性进度?
从登录功能中删除 else if 大小写。这个。
else if (this.state.loaded === false) {
return (
<LinearProgress /> // for loading
);
}
并在登录输入字段下方的渲染中添加一个三元条件来检查状态,如果状态为 false 则渲染
<LinearProgress />
,并且当登录使状态为 true 时,将移至下一页。
<input
type="submit"
value="Login"
className="logbtn"
onClick={this.login}
/>
{(this.state.loaded)?null: <LinearProgress />}
根据您的沙箱,您需要添加/更改一些内容
loaded
重命名为 isLoading
参数到您的 state
,这样会更容易理解它的可用性 this.state = {
loginEmail: "",
loginPassword: "",
error: {},
redirect: false,
isLoading: false,
history: PropTypes.object.isRequired
};
true
,有多种方法可以做到这一点,但最简单的是直接在 isLoading
函数中更改 login
finally
承诺处理程序,以便在调用后将加载状态更改为 false,无论成功还是失败。login() {
const { history } = this.props;
this.setState({isLoading:true});
PostData("api/users/login", this.state)
.then(result => {
let responseJSON = result;
if (responseJSON.success === true) {
localStorage.setItem("loginEmail", this.state.loginEmail);
localStorage.setItem("id", responseJSON.user.id);
history.push("/Home"); // when successfully login, it will go to Home Page
} else if (responseJSON.success === false) {
alert("Wrong User Credential");
}
})
.catch(error => {
console.log(error);
})
.finally(() => this.setState({ isLoading : false }));
}
<LinearProgress />
元素并为其设置条件。在你的情况下,isLoading
是true
。您可以通过添加以下行将元素放置在渲染内的任何位置{this.state.isLoading && <LinearProgress />}