我正在使用带有状态管理“ mobx-react”的react npm,所有共享状态都在“ AppStore”中。应用刷新后,“ AppStore.signIn()”会从本地存储中获取用户并设置“ AppStore.signedUser”,否则该值将无法定义。 该组件将呈现用户(如果存在), 但如果不是,则应用程序应在渲染之前重定向到“ / signup”。 由于该应用的渲染速度高于完成“登录”所需的时间, 即使存在用户,刷新时也始终重定向到注册。 我该如何仅在AppStore.signIn()完成后重定向?
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import AppStore from './store/AppStore';
class App extends Component {
state = {
isLogged: false,
isCheckedLogged: false,
}
async componentWillMount() {
await AppStore.signIn();
if (AppStore.signedUser) {
this.setState({ isLogged: true });
} else {
this.setState({ isLogged: false });
}
this.state.isCheckedLogged = true;
}
render() {
return (
<div className="App">
<HashRouter>
<nav className="main-nav">
<NavLink exact to="/" className="nav-link">Home</NavLink>
<NavLink to="/signup" className="nav-link">Signup</NavLink>
</nav>
<Switch>
<Route exact path="/" render={() => this.state.isLogged ?
(<Home store={AppStore} history={HashRouter} />) :
(<Redirect to="/signup"/>)} />
<Route exact path="/signup" render={() =>
(<Signup store={AppStore} history={HashRouter} />)} />
</Switch>
</HashRouter>
</div>);
}
}
export default observer(App);
答案 0 :(得分:0)
您可以将默认状态为loading: true
。在渲染函数中,检查组件是否正在加载,如果正在加载,则显示加载器,或者根据需要显示任何内容。完成signIn()
函数后,将loading设置为false,然后react将自动重新渲染并适当地重定向用户。看看一些代码:
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import AppStore from './store/AppStore';
class App extends Component {
state = {
isLogged: false,
loading: true,
isCheckedLogged: false,
}
async componentWillMount() {
await AppStore.signIn();
if (AppStore.signedUser) {
this.setState({ isLogged: true, loading: false });
} else {
this.setState({ isLogged: false, loading: false });
}
this.state.isCheckedLogged = true;// not sure this can help, and it's also not
// a right way to set state
}
render() {
return (
<div className="App">
{! this.state.loading && (
<HashRouter>
<nav className="main-nav">
<NavLink exact to="/" className="nav-link">Home</NavLink>
<NavLink to="/signup" className="nav-link">Signup</NavLink>
</nav>
<Switch>
<Route exact path="/" render={() => this.state.isLogged ?
(<Home store={AppStore} history={HashRouter} />) :
(<Redirect to="/signup"/>)} />
<Route exact path="/signup" render={() =>
(<Signup store={AppStore} history={HashRouter} />)} />
</Switch>
</HashRouter>
)}
</div>);
}
}
export default observer(App);