javascript-组件渲染为时过早

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

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

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

import React,{ Component } from 'react'
import { connect } from 'react-redux'
import { Route } from 'react-router-dom'

class PrivateRoute extends Component {
  render() {
    const { component: Component,...rest } = this.props
    console.log(this.props)

    return (
      <Route {...rest} render={(props) => (props.auth ? <Component {...props} /> : props.history.push('/login'))} />
    )
  }
}

function mapStateToProps({ auth }) {
  return { auth }
}

export default connect(mapStateToProps)(PrivateRoute)
最佳答案
我没有在这里使用redux,但是我想您会明白的.希望这会有所帮助,并随时提出任何问题!

import React,{ Component } from "react";
import { BrowserRouter,Route,Switch,Redirect } from "react-router-dom";

import Dashboard from "path/to/pages/Dashboard";

class App extends Component {
  state = {
    isLoggedIn: null,};

  componentDidMount () {
    // to survive F5
    // when page is refreshed all your in-memory stuff
    // is gone
    this.setState({ isLoggedIn: !!localStorage.getItem("sessionID") });
  }

  render () {
    return (
      <BrowserRouter>
        <Switch>
          <PrivateRoute
            path="/dashboard"
            component={Dashboard}
            isLoggedIn={this.state.isLoggedIn}
          />
          <Route path="/login" component={Login} />

          {/* if no url was matched -> goto login page */}
          <Redirect to="/login" />
        </Switch>
      </BrowserRouter>
    );
  }
}

class PrivateRoute extends Component {
  render () {
    const { component: Component,isLoggedIn,...rest } = this.props;

    return (
      <Route
        {...rest}
        render={props =>
          isLoggedIn ? <Component {...props} /> : <Redirect to="/login" />
        }
      />
    );
  }
}

class Login extends Component {
  state = {
    login: "",password: "",sessionID: null,};

  componentDidMount () {
    localStorage.removeItem("sessionID");
  }

  handleFormSubmit = () => {
    fetch({
      url: "/my-app/auth",method: "post",body: JSON.strigify(this.state),})
      .then(response => response.json())
      .then(data => {
        localStorage.setItem("sessionID",data.ID);

        this.setState({ sessionID: data.ID });
      })
      .catch(e => {
        // error handling stuff
      });
  };

  render () {
    const { sessionID } = this.state;

    if (sessionID) {
      return <Redirect to="/" />;
    }

    return <div>{/* login form with it's logic */}</div>;
  }
}
原文链接:https://www.f2er.com/js/531297.html

猜你在找的JavaScript相关文章