简体   繁体   中英

React conditional rendering not triggering?

I am trying to change the contents of my Navbar and my Router via useContext and conditional rendering. This is my App.js:


import "./App.css";
import axios from "axios";
import { AuthContextProvider } from "./context/AuthContext";
import MyRouter from "./MyRouter";

axios.defaults.withCredentials = true;

function App() {
  return (
    <AuthContextProvider>
      <MyRouter />
    </AuthContextProvider>
  );
}

export default App; 

This is my Router:

import React, { useContext } from "react";
import AuthContext from "./context/AuthContext";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from "react-router-dom";
import MyNavBar from "./components/MyNavbar";
import "./App.css";
import Home from "./components/pages/Home";
import AboutUs from "./components/pages/AboutUs";
import Register from "./components/pages/Register";
import MyFooter from "./components/MyFooter";
import login from "./components/pages/login";
import ProfilePage from "./components/pages/ProfilePage";
function MyRouter() {
  const { loggedIn } = useContext(AuthContext);
  return (
    <Router>
      <MyNavBar />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/about-us" component={AboutUs} />
        {loggedIn === false && (
          <>
            <Route exact path="/register" component={Register} />
            <Route exact path="/login" component={login} />
          </>
        )}
        {loggedIn === true && (
          <>
            <Route exact path="/profile" component={ProfilePage} />
          </>
        )}

        <Redirect to="404" />
      </Switch>
      <MyFooter />
    </Router>
  );
}

export default MyRouter;

My Navbar's conditional rendering works in the same way as the router. My problem is that neither of the conditional rendering fragments are working. For example, when my application starts, users are not logged in and the "loggedIn" value is false. With this logic, the routes "register" and "login" should be accessible, but they are not. Any advice or help would be greatly appreciated as I am quite new to using React.

Here is a screenshot of my console upon loading the application

This is my "AuthContext":

const AuthContext = createContext();
function AuthContextProvider(props) {
  const [loggedIn, setLoggedIn] = useState(undefined);
  async function getLoggedIn() {
    const loggedInRes = await axios.get(
      "http://localhost:5000/api/users/loggedIn"
    );
    setLoggedIn(loggedInRes.data);
  }

  useEffect(() => {
    getLoggedIn();
  }, []);
  return (
    <AuthContext.Provider value={{ loggedIn, getLoggedIn }}>
      {props.children}
    </AuthContext.Provider>
  );
}
export default AuthContext;
export { AuthContextProvider };

Edited:

Instead of using your conditions in your main route, you can create a ProtectedRoute which Routes your component according to your condition.

    import React, { useEffect } from "react";
    import { Route, Redirect, useHistory } from "react-router-dom";
    const ProtectedRoute = ({ component: Component, ...rest }) => {
        const { loggedIn } = useContext(AuthContext);
        return (
            <Route
                {...rest}
                render={(props) =>
                    loggedIn() ? (
                        <Component {...props} />
                    ) : (
                        <Redirect to='/login' />
                    )
                }
            />
        );
    };
export default ProtectedRoute;
  • In your component you can change your logic with this:
 <ProtectedRoute exact path="/" component={Home} /> <ProtectedRoute exact path="/about-us" component={AboutUs}/> <Route exact path="/register" component={Register} /> <Route exact path="/login" component={login} /> <ProtectedRoute exact path="/profile" component={ProfilePage} />

This means that if you wanna protect a route you should route it with ProtectedRoute otherwise classic react route.

You can read about that ProtectedRoute concept here

Thanks for all the help guys, I learned a lot about the ProtectedRoute concept. My issue came from my Navigation Bar component. Instead of declaring my variable as an object, I declared loggedin like const loggedIn = useContext(AuthContext); All my errors were solved once I changed it to const { loggedIn } = useContext(AuthContext);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM