首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >条件有效且多次验证,但一次除外

问条件有效且多次验证,但一次除外
EN

Stack Overflow用户
提问于 2020-12-08 03:16:09
回答 1查看 63关注 0票数 0

我有一个有5个页面的react路由器,如果我有一个用户登录,那么我会检查其中的4个页面,以便他是否被重定向,或者显示组件。

它对于前3页非常有效,但是对于最后的"/create-channel",由于某些原因,它不能工作。

loggedIn的值为true,对于前3个页面,它将使条件有效,但对于后3个页面,似乎总是将我重定向到登录页面。

我也尝试过这样做(反转条件):

代码语言:javascript
复制
{loggedIn ? <CreateChannel/> : <Redirect to="/login"/>}

至

代码语言:javascript
复制
{loggedIn ? <Redirect to="/login"/>: <CreateChannel/>}

但我仍然被重定向到登录页面。我不知道发生了什么。create-channel页面内部没有任何重定向。

App.js

代码语言:javascript
复制
import {useEffect, useState} from 'react'
import './App.css';
import axios from 'axios';
/** @jsx jsx */
import { jsx } from '@emotion/core'
// Local
import Footer from './Footer'
import Header from './Header'
import Main from './Main'
import Login from './Login'
import Register from './Register'
import CreateChannel from './CreateChannel'
import { ChannelsContext } from './Contexts/ChannelsContext'
import { UserContext } from './Contexts/UserContext';
import { LoggedInContext } from './Contexts/LoggedInContext';
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import { makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import { getCookie } from './utils/cookies';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from "react-router-dom";


export default () => {
  //VARIABLES & HOOKS
  const styles = useStyles();
  const [username, setUsername] = useState("My Account")
  const [channels, setChannels] = useState([{id: 0, name: 'channel 0'}]);
  const [drawerMobileVisible, setDrawerMobileVisible] = useState(false)
  const [darkMode, setDarkMode] = useState(false)
  const [loggedIn, setLoggedIn] = useState(false);

  useEffect( () => {
    const checkLoggedIn = async () => {
      if(typeof getCookie('authorization') === "undefined"){
        setLoggedIn(false);
        console.log("Not logged in")
      }else{
        setLoggedIn(true);
        console.log("Logged in. Redirecting...")
      }
    }
    checkLoggedIn()
  }, [loggedIn])

  const darkModeToggleListener = () => {
    setDarkMode(!darkMode)
    console.log(contextLoggedIn.loggedIn)
  }
  const drawerToggleListener = () => {
    setDrawerMobileVisible(!drawerMobileVisible)
  }

  const contextLoggedIn = {
    loggedIn: loggedIn,
    setLoggedInContext: setLoggedIn
  }

  const contextChannels = {
    channels: channels,
    setChannelsContext: setChannels
  }
  const contextUser = {
    username: username,
    setUserContext: setUsername
  }


  //RENDER
  return (
    <ThemeProvider theme={theme}>
    <UserContext.Provider value={contextUser}>
    <LoggedInContext.Provider value={contextLoggedIn}>
    <ChannelsContext.Provider value={contextChannels}>
    <CssBaseline />
      <Router>
        <div className={styles.root}>
          <Header 
            drawerToggleListener={drawerToggleListener}
            darkModeToggleListener = {darkModeToggleListener}
          />

          <Switch>
            <Route path="/login">
              {loggedIn ? <Redirect to="/welcome"/> : <Login onUser={setUsername}/>}
            </Route>
            <Route path="/register">
              {loggedIn ? <Redirect to="/welcome"/> : <Register/>}
            </Route>
            <Route path="/welcome">
              {loggedIn ? <Main drawerMobileVisible={drawerMobileVisible} /> : <Redirect to="/login"/>}
            </Route>
            <Route path="/create-channel">
              {loggedIn ? <CreateChannel/> : <Redirect to="/login"/>}
            </Route>
            <Route path="/"> 
              <Redirect to="/login" />
            </Route>
          </Switch>

          <Footer />
        </div>
      </Router>
    </ChannelsContext.Provider>
    </LoggedInContext.Provider>
    </UserContext.Provider>
    </ThemeProvider>
  );
}

编辑: CreateChannel.js

代码语言:javascript
复制
import { useContext, useState } from 'react';
/** @jsx jsx */
import { jsx } from '@emotion/core'
// Layout
import { useTheme } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import ForumIcon from '@material-ui/icons/Forum';
import { UserContext } from './Contexts/UserContext'
import axios from 'axios';

/** INSPIRED FROM MUI DOCS https://material-ui.com/components/text-fields/ */

const useStyles = (theme) => ({
  root: {
    flex: '1 1 auto',
    background: theme.palette.background,
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    '& > div': {
      marginLeft: 'auto',
      marginRight: 'auto',
      marginTop: '1%',
      marginBottom: '1%',
      width: '30%',
    },
  },
  password:{
    width:'100%'
  },
  center:{
    width: 'auto',
  },
  icon:{
    width: '100%',
    height: '150px'
  }
});

export default () => {
  const [name, setName] = useState(null)
  const [users, setUsers] = useState(null)
  const [userNotFound, setUserNotFound] = useState(false)
  const contextUser = useContext(UserContext)

  const styles = useStyles(useTheme());

  const handleCreateChannel = async () => {
    //First check if all users exists
    let userUnknown = false;
    let array = users.split(';')

    for(const elem of array){
      await axios.get(`http://localhost:3001/users/${elem}`,{}, {withCredentials: true})
      .then(function (response){
        // eslint-disable-next-line
      }).catch(function (error){
        if(error.response.status === 404){
          userUnknown = true
        }
      })
    }

    //Then add yourself
    array.push(contextUser.username)

    //And finally add to db if all users are known
    if(!userUnknown){
      await axios.post('http://localhost:3001/channels',{
        name: name,
        users: array
      }, {withCredentials: true}).then(function (response){
        window.location.href = '/welcome';
      }).catch(function (error){
        if(error.response.status === 404){
        }
        else if(error.response.status === 401){
        }
      })
    }
    else{
      setUserNotFound(true)
    }
  }

  return (
    <div css={styles.root} >
      <Grid style={styles.center}>
        <ForumIcon
          color='primary'
          css={styles.icon}
        />
      </Grid>

      <Grid style={styles.center}>
        <Typography variant='h2' color='primary'>
          Create a channel
        </Typography>
      </Grid>

      <Grid>
        <TextField
          variant="outlined"
          id="name"
          label="Channel name"
          name="name"
          autoFocus
          fullWidth
          onChange={(e) => setName(e.target.value)}
        />
      </Grid>

      <Grid>
        <TextField
          error = {userNotFound}
          variant="outlined"
          id="users"
          label="Users (separated by a coma ) | BETA"
          name="Users"
          fullWidth
          helperText = {userNotFound ? "At least one user does not exist." : "Do not include yourself (automatically added)."}
          onChange={(e) => setUsers(e.target.value)}
        />
      </Grid>
        
      <Grid>
        <Button
          type="submit"
          margin = 'normal'
          variant="contained"
          color="primary"
          fullWidth
          onClick = {handleCreateChannel}
        >
          Create
        </Button>
      </Grid>

    </div>
  );
}
EN

回答 1

Stack Overflow用户

发布于 2020-12-08 03:56:19

嘿,SoaAlex,欢迎来到社区,

我认为这是因为您的路径中有连字符。我不确定这是否可能,所以我搜索了一下,找到了this。您能否验证一下并尝试不使用连字符?您可以尝试:

代码语言:javascript
复制
<Route path="/createChannel"> 

或

代码语言:javascript
复制
<Route path="/create_channel">
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65187975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档