在 React JS 中,在触发任何代码之前等待页面加载的正确方法是什么?
设想:
登录服务对用户进行身份验证,然后将他们(使用 cookie)重定向到 React 应用程序。
然后,React 应用程序会立即搜索 cookie 并根据端点对其进行验证。
但我遇到的问题是,当用户在登录服务中通过身份验证,然后转发到 React App 时,应用程序在加载 cookie 之前加载速度非常快。
触发代码的正确方法是什么?我尝试包装一个componentDidMount(),没有用!
最佳答案
我建议您在应用程序的主要组件(通常是 App.jsx)中使用一个状态来控制加载。当您启动应用程序时,状态将为真,只有在检查完所有您需要检查的内容后,它才会变为假。如果状态正在加载,您将显示微调器或您想要的任何内容,当它未加载时,网站:
class App extends Component {
constructor(props) {
super(props);
this.state = { loading: true }
}
componentDidMount () {
checkToken()
.then(() => this.setState({ loading: false });
}
if (loading) {
return <Spinner /> // or whatever you want to show if the app is loading
}
return (
...rest of you app
)
}
如果有任何疑问,请告诉我。
关于javascript - React - 等待页面加载的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61596860/