javascript-组件渲染为时过早

前端之家收集整理的这篇文章主要介绍了javascript-组件渲染为时过早 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图创建一个PrivateRoute(HOC)来测试用户是否已通过身份验证(在redux存储中检查“ auth”是否存在),然后再将其发送到实际路由.问题是在我的身份验证出现在redux存储中之前,privateroute完成了.

console.log第一次运行两次,auth没有出现在存储中,但是第二次出现,但是到那时,它已经将用户路由到登录屏幕了.提取完成?当我只想有条件地显示某些内容(例如登录/注销按钮)时,我知道如何执行此条件,但是当尝试有条件地路由某人时,这种方法无效.

  1. import React,{ Component } from 'react'
  2. import { connect } from 'react-redux'
  3. import { Route } from 'react-router-dom'
  4. class PrivateRoute extends Component {
  5. render() {
  6. const { component: Component,...rest } = this.props
  7. console.log(this.props)
  8. return (
  9. <Route {...rest} render={(props) => (props.auth ? <Component {...props} /> : props.history.push('/login'))} />
  10. )
  11. }
  12. }
  13. function mapStateToProps({ auth }) {
  14. return { auth }
  15. }
  16. export default connect(mapStateToProps)(PrivateRoute)
最佳答案
我没有在这里使用redux,但是我想您会明白的.希望这会有所帮助,并随时提出任何问题!

  1. import React,{ Component } from "react";
  2. import { BrowserRouter,Route,Switch,Redirect } from "react-router-dom";
  3. import Dashboard from "path/to/pages/Dashboard";
  4. class App extends Component {
  5. state = {
  6. isLoggedIn: null,};
  7. componentDidMount () {
  8. // to survive F5
  9. // when page is refreshed all your in-memory stuff
  10. // is gone
  11. this.setState({ isLoggedIn: !!localStorage.getItem("sessionID") });
  12. }
  13. render () {
  14. return (
  15. <BrowserRouter>
  16. <Switch>
  17. <PrivateRoute
  18. path="/dashboard"
  19. component={Dashboard}
  20. isLoggedIn={this.state.isLoggedIn}
  21. />
  22. <Route path="/login" component={Login} />
  23. {/* if no url was matched -> goto login page */}
  24. <Redirect to="/login" />
  25. </Switch>
  26. </BrowserRouter>
  27. );
  28. }
  29. }
  30. class PrivateRoute extends Component {
  31. render () {
  32. const { component: Component,isLoggedIn,...rest } = this.props;
  33. return (
  34. <Route
  35. {...rest}
  36. render={props =>
  37. isLoggedIn ? <Component {...props} /> : <Redirect to="/login" />
  38. }
  39. />
  40. );
  41. }
  42. }
  43. class Login extends Component {
  44. state = {
  45. login: "",password: "",sessionID: null,};
  46. componentDidMount () {
  47. localStorage.removeItem("sessionID");
  48. }
  49. handleFormSubmit = () => {
  50. fetch({
  51. url: "/my-app/auth",method: "post",body: JSON.strigify(this.state),})
  52. .then(response => response.json())
  53. .then(data => {
  54. localStorage.setItem("sessionID",data.ID);
  55. this.setState({ sessionID: data.ID });
  56. })
  57. .catch(e => {
  58. // error handling stuff
  59. });
  60. };
  61. render () {
  62. const { sessionID } = this.state;
  63. if (sessionID) {
  64. return <Redirect to="/" />;
  65. }
  66. return <div>{/* login form with it's logic */}</div>;
  67. }
  68. }

猜你在找的JavaScript相关文章