【发布时间】:2021-05-18 13:14:58
【问题描述】:
我用 React 创建了一个登录系统,它在用户登录时存储一个会话。当页面重新加载时,我添加了一个函数来检查会话是否存在,然后将 setState() 到 true或false。
由于我是 React 新手,我不确定如何执行此功能。请在下面查看我的 App.js 代码:
import React from 'react';
import './css/App.css';
import LoginForm from "./LoginForm";
import Dashboard from "./Dashboard";
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
renderLoginForm: true
};
this.handleLoginFormMount = this.handleLoginFormMount.bind(this);
}
handleLoginFormMount() {
this.setState({
renderLoginForm: false
});
}
// Check session function.
checkSession() {
fetch('/check-session', {
credentials: 'include'
})
.then((response) => {
return response.json();
})
.then((sessionResult) => {
if (sessionResult.username) {
console.log('false');
this.setState({
renderLoginForm: false
});
} else {
console.log('true');
this.setState({
renderLoginForm: true
});
}
})
.catch((error) => {
console.log('Error: ', error);
});
}
render() {
checkSession();
return (
<div className="App">
{this.state.renderLoginForm ? <LoginForm mountLoginForm={this.handleLoginFormMount} /> : null}
{this.state.renderLoginForm ? null : <Dashboard />}
</div>
);
}
}
export default App;
在此位置有checkSession() 在加载页面时会在控制台中输出以下内容:
Line 50: 'checkSession' is not defined no-undef
如果我把函数放在class App extends React.Component {}之外,那么它告诉我我不能设置未定义的状态。
【问题讨论】:
-
首先由于checkSession是组件函数,你需要使用this.checkSession();调用它。用于检查用户会话是否有效。您在 lefecycle 方法中进行 api 调用。在我知道您使用的是什么版本的 reactjs 之前,我无法告诉您正确的生命周期。请告知
-
感谢您的回复。我正在使用最新版本的 React。
-
旁注:您的
fetch呼叫缺少成功检查,this post on my anemic little blog 中的详细信息。
标签: javascript reactjs