条件有效且经过多次验证,但一次除外



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

它完美地适用于前3页,但适用于最后一页/创建频道";,由于某种原因它不起作用。

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

我也试过这样做(扭转条件(:

{loggedIn ? <CreateChannel/> : <Redirect to="/login"/>}

{loggedIn ? <Redirect to="/login"/>: <CreateChannel/>}

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

App.js

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

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>
);
}

嗨,SoaAlex,欢迎来到社区,

我想这是因为你的路径上有连字符。我不确定这是否可能,所以我搜索了一下,找到了这个。你能核实一下并试着不使用连字符吗?你可以试试:

<Route path="/createChannel"> 

<Route path="/create_channel">

最新更新