我用React创建了一个登录系统,该系统在用户登录时存储会话。重新加载页面后,我添加了一个功能,该功能应检查会话是否存在,然后将setState()
更改为{ {1}}或true
。
由于我是React的新手,所以我不确定如何执行此功能。请在下面查看 App.js 的代码:
false
在加载页面时,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
之外,则表明我无法设置未定义状态。
答案 0 :(得分:4)
在加载页面时,
checkSession()
处于此位置会在控制台中输出以下内容:Line 50: 'checkSession' is not defined no-undef
那是因为它是一种方法,但是您将其称为独立函数。呼叫应为this.checkSession();
。但是请继续阅读。
分别:
render
函数必须是纯函数,不能有诸如更改状态之类的副作用。而是将任何副作用代码放在componentDidMount
中;从该生命周期方法的文档中获取:
如果您需要从远程端点加载数据,这是实例化网络请求的好地方。
请确保您的组件针对原始状态(会话检查之前)和更新后的状态(会话检查之后)正确呈现。
有关生命周期方法以及此类in the documentation的更多信息。
或者,如果没有会话,该组件无法执行任何有用的操作,则可以将会话检查移至其父组件,并让父组件仅在具有会话检查结果时才呈现此子组件。
答案 1 :(得分:1)
功能组件:在我的例子中,我希望我的代码在组件呈现在屏幕上之前运行。 useLayoutEffect
是 React 为这个确切目的提供的钩子。
import React, { useLayoutEffect } from "react";
...
const App = () => {
useLayoutEffect(() => {
//check local token or something
}, []);
}
阅读更多:https://reactjs.org/docs/hooks-reference.html#uselayouteffect