Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React JS-重定向到除主页外的登录_Javascript_Reactjs - Fatal编程技术网

Javascript React JS-重定向到除主页外的登录

Javascript React JS-重定向到除主页外的登录,javascript,reactjs,Javascript,Reactjs,我正在学习使用React JS。 我有下一页 家 登录 注 创建注释 我的情况如下 无需登录即可访问主页 未登录,无法访问备注和创建备注 如何使上述案例起作用? 下面是我编写的代码片段: index.js import App from "./App"; import * as serviceWorker from "./serviceWorker"; ReactDOM.render( <BrowserRouter> // from

我正在学习使用React JS。 我有下一页

  • 登录
  • 创建注释
我的情况如下

  • 无需登录即可访问主页
  • 未登录,无法访问备注和创建备注
  • 如何使上述案例起作用? 下面是我编写的代码片段:

    index.js

    import App from "./App";
    import * as serviceWorker from "./serviceWorker";
    
    ReactDOM.render(
      <BrowserRouter> // from "react-router-dom"
        <App />
      </BrowserRouter>,
      document.getElementById("root")
    );
    
    serviceWorker.unregister();
    
    import React from "react";
    import { Route, Switch } from "react-router-dom";
    
    const Routes = () => {
      return (
        <Switch>
          <Route exact path={["/", "/home"]} component={Home} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/note" component={Note} />
          <Route exact path="/note/create" component={NoteCreate} />
          <Route exact path="/profile" component={Profile} />
        </Switch>
      );
    };
    
    export default Routes;
    
    从“/App”导入应用程序;
    将*作为serviceWorker从“/serviceWorker”导入;
    ReactDOM.render(
    //从“反应路由器dom”
    ,
    document.getElementById(“根”)
    );
    serviceWorker.unregister();
    
    App.js作为入门主页

    import React, { Component } from "react";
    import AuthService from "./services/auth.service";
    import Routes from "./config/routes";
    // Lot of import bootstrap dan font-awesome and css
    
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.logOut = this.logOut.bind(this);
    
        this.state = {
          currentUser: undefined,
          backendSupportInformation: undefined,
        };
      }
    
      componentDidMount() {
        const user = AuthService.getCurrentUser();
        if (user) {
          this.setState({
            currentUser: user,
            backendSupportInformation: user.backend,
          });
        }
      }
    
      logOut() {
        AuthService.logout();
      }
    
      render() {
        const { currentUser, backendSupportInformation } = this.state;
        return (
          <div>
            <header>
              <nav className="navbar navbar-expand-sm navbar-dark bg-dark">
                // some of link here
              </nav>
            </header>
    
            <main role="main" className="container-fluid mt-3">
              <Routes /> // use react-route-dom
            </main>
    
          </div>
        );
      }
    }
    
    export default App;
    
    import React,{Component}来自“React”;
    从“/services/auth.service”导入AuthService;
    从“/config/Routes”导入路由;
    //大量导入引导程序和css
    类应用程序扩展组件{
    建造师(道具){
    超级(道具);
    this.logOut=this.logOut.bind(this);
    此.state={
    当前用户:未定义,
    后端支持信息:未定义,
    };
    }
    componentDidMount(){
    const user=AuthService.getCurrentUser();
    如果(用户){
    这是我的国家({
    当前用户:用户,
    后端支持信息:user.backend,
    });
    }
    }
    注销(){
    AuthService.logout();
    }
    render(){
    const{currentUser,backendSupportInformation}=this.state;
    返回(
    //这里有一些链接
    //使用react-route-dom
    );
    }
    }
    导出默认应用程序;
    
    Routes.js

    import App from "./App";
    import * as serviceWorker from "./serviceWorker";
    
    ReactDOM.render(
      <BrowserRouter> // from "react-router-dom"
        <App />
      </BrowserRouter>,
      document.getElementById("root")
    );
    
    serviceWorker.unregister();
    
    import React from "react";
    import { Route, Switch } from "react-router-dom";
    
    const Routes = () => {
      return (
        <Switch>
          <Route exact path={["/", "/home"]} component={Home} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/note" component={Note} />
          <Route exact path="/note/create" component={NoteCreate} />
          <Route exact path="/profile" component={Profile} />
        </Switch>
      );
    };
    
    export default Routes;
    
    从“React”导入React;
    从“react router dom”导入{Route,Switch};
    常数路由=()=>{
    返回(
    );
    };
    导出默认路径;
    
    现在我在NoteComponent中这样做

    NoteComponent

    export default class Note extends Component {
      state = {
        redirect: null,
        userReady: false,
      };
      
      componentDidMount() {
        const currentUser = AuthService.getCurrentUser();
        
        if (!currentUser) this.setState({ redirect: "/home" });
        this.setState({ currentUser: currentUser, userReady: true });
    
        this.retrieveAll();
      }
    
      render() {
        if (this.state.redirect) {
          
          // pass message that you need login first to access this note page
          return <Redirect to={this.state.redirect} />;
        }
    }
    
    
    导出默认类注释扩展组件{
    状态={
    重定向:null,
    userReady:false,
    };
    componentDidMount(){
    const currentUser=AuthService.getCurrentUser();
    if(!currentUser)this.setState({redirect:“/home”});
    this.setState({currentUser:currentUser,userReady:true});
    this.retrieveAll();
    }
    render(){
    if(this.state.redirect){
    //传递您需要先登录才能访问此备注页的消息
    返回;
    }
    }
    
    我不想在NoteCreate组件中重复我的自我?
    非常感谢您的任何建议。

    作为一个开始,我不确定您正在使用哪些资源来学习反应,但从现在起,我强烈建议您学习一门现代课程,除了获取错误边界(其中包含)之外,没有理由编写类组件

    关于手头的问题,您没有特别提到任何错误,因此这似乎是一个“我应该如何处理”的问题,而不是实际修复某个问题?如果有具体错误,请告诉我,我将尝试调整我的答案以进一步提供帮助


    我建议您将Notes组件中的逻辑重构为一个组件本身,这样您就可以用它包装路由。将路由是否经过身份验证的信息存储到中,然后用该上下文提供程序包装路由,这样您就可以在子组件中使用该上下文,而无需复制该日志每个页面上都有ic。

    作为一个开始说明,不确定您正在使用哪些资源来学习反应,但从现在起,我强烈建议您研究一门现代课程,该课程除了获取错误边界(其中包含)之外,没有理由编写类组件

    关于手头的问题,您没有特别提到任何错误,因此这似乎是一个“我应该如何处理”的问题,而不是实际修复某个问题?如果有具体错误,请告诉我,我将尝试调整我的答案以进一步提供帮助


    我建议您将Notes组件中的逻辑重构为一个组件本身,这样您就可以用它包装路由。将路由是否经过身份验证的信息存储到中,然后用该上下文提供程序包装路由,这样您就可以在子组件中使用该上下文,而无需复制该日志每个页面上都有ic。

    您需要创建一个
    路由器WithAuth
    组件,并使用该组件,而不是直接使用
    路由器
    ,如下所示:

    export default class RouteWithAuth extends Component {
      state = {
        redirect: null,
        userReady: false,
      };
    
      componentDidMount() {
        const currentUser = AuthService.getCurrentUser();
    
        if (!currentUser) this.setState({ redirect: "/home" });
        this.setState({ currentUser: currentUser, userReady: true });
    
        this.retrieveAll();
      }
    
      render() {
        const { redirect, userReady } = this.state;
    
        if (redirect) {
          // pass message that you need login first to access this note page
          return <Redirect to={this.state.redirect} />;
        } else if (userReady) {
          return (
            <Route
              exact={props.exact}
              path={props.path}
              component={props.component}
            />
          );
        } else {
          return <div>Loading....</div>;
        }
      }
    }
    
    
    export default function RouteWithAuth() {
      const [redirect, setRedirect] = useState(null);
      const [userReady, setUserReady] = useState(false);
    
      useEffect(() => {
        const currentUser = AuthService.getCurrentUser();
    
        if (!currentUser) {
          setRedirect("/home");
          return;
        }
    
        //Do Something with the currentUser such as storing it in redux store or in context for later use cases
        setUserReady(true);
      }, []);
    
      if (redirect) {
        return <Redirect to={redirect} />;
      } else if (userReady) {
        return (
          <Route
            exact={props.exact}
            path={props.path}
            component={props.component}
          />
        );
      } else {
        return <div>Loading....</div>;
      }
    }
    

    您需要创建一个
    RouterWithAuth
    组件并使用它,而不是直接使用
    Router
    ,如下所示:

    export default class RouteWithAuth extends Component {
      state = {
        redirect: null,
        userReady: false,
      };
    
      componentDidMount() {
        const currentUser = AuthService.getCurrentUser();
    
        if (!currentUser) this.setState({ redirect: "/home" });
        this.setState({ currentUser: currentUser, userReady: true });
    
        this.retrieveAll();
      }
    
      render() {
        const { redirect, userReady } = this.state;
    
        if (redirect) {
          // pass message that you need login first to access this note page
          return <Redirect to={this.state.redirect} />;
        } else if (userReady) {
          return (
            <Route
              exact={props.exact}
              path={props.path}
              component={props.component}
            />
          );
        } else {
          return <div>Loading....</div>;
        }
      }
    }
    
    
    export default function RouteWithAuth() {
      const [redirect, setRedirect] = useState(null);
      const [userReady, setUserReady] = useState(false);
    
      useEffect(() => {
        const currentUser = AuthService.getCurrentUser();
    
        if (!currentUser) {
          setRedirect("/home");
          return;
        }
    
        //Do Something with the currentUser such as storing it in redux store or in context for later use cases
        setUserReady(true);
      }, []);
    
      if (redirect) {
        return <Redirect to={redirect} />;
      } else if (userReady) {
        return (
          <Route
            exact={props.exact}
            path={props.path}
            component={props.component}
          />
        );
      } else {
        return <div>Loading....</div>;
      }
    }
    

    您研究过吗?通常您会创建经过身份验证的路由,该路由将弹回未经身份验证的用户。将身份验证状态存储在上下文提供程序或其他一些应用程序状态管理模式(如redux)中。您是否尝试实施我的解决方案?正在……研究过吗?通常您会创建经过身份验证的路由,该路由将弹回未经身份验证的用户icated用户。将身份验证状态存储在上下文提供程序或其他应用程序状态管理模式(如redux)中。您是否尝试实施我的解决方案?正在工作…似乎我需要更多时间学习挂钩。我来自OOP范例。这是一个新的东西。顺便说一句,谢谢。我需要更多时间学习挂钩。我来自OOP范例。这是一个新的东西新的。顺便说一句,谢谢