Javascript 链接标签会更改我的历史位置,但会更改回原始主页React.js
所以我在一个项目上遇到了这个问题,我已经做了两天了,我不知道为什么。我以前在我的Web应用程序中使用过React-router dom,在我使用React.js的所有月份中,我从未遇到过这个问题。我基本上有我的交换机组件、围绕App.js的BrowserRouter等等,但每次单击指向我的新路由“/注册”的链接,URL将更改几秒钟,然后更改回我的登录主页。这在我没有做任何事情或点击任何东西的情况下发生。我尝试将链接标记属性从=“/register”更改为href=“/register”,但没有成功。这太气人了,这是我的密码: Index.jsJavascript 链接标签会更改我的历史位置,但会更改回原始主页React.js,javascript,reactjs,react-router-dom,Javascript,Reactjs,React Router Dom,所以我在一个项目上遇到了这个问题,我已经做了两天了,我不知道为什么。我以前在我的Web应用程序中使用过React-router dom,在我使用React.js的所有月份中,我从未遇到过这个问题。我基本上有我的交换机组件、围绕App.js的BrowserRouter等等,但每次单击指向我的新路由“/注册”的链接,URL将更改几秒钟,然后更改回我的登录主页。这在我没有做任何事情或点击任何东西的情况下发生。我尝试将链接标记属性从=“/register”更改为href=“/register”,但没有成
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
从“react dom”导入ReactDOM;
导入“./index.css”;
从“./App”导入应用程序;
从“react router dom”导入{BrowserRouter};
ReactDOM.render(
,
document.getElementById('root'))
);
App.js
import React,{Component} from 'react';
import { Router, Switch, Route, withRouter, Link} from 'react-router-dom'
import HomePage from "./components/HomePage";
import Register from "./components/Register"
import Dashboard from "./components/Dashboard"
// import Link from '@material-ui/core/Link';
// import { background } from "./images/7f76e8e7692375107e5998013155af0d.jpg";
// import { TravelerEffect, MosaicGroundEffect, OceanEffect,
// RainEffect, SeaWaveEffect, SnowFallEffect, SnowFallSlowEffect,
// SpacingEffect, CloudWaveEffect
// } from 'react-background-animation'
class App extends Component {
state = {
user: {
email: "",
username: "",
is_active: "",
first_name: "",
last_name: "",
bio: "",
age: "",
birth_place: "",
school: "",
occupation: "",
what_are_you_seeking_on_site: "",
profile_pic: null,
loginErrors: "",
},
token: "",
}
handleResponse (resp) {
console.log(resp.user);
if (resp.user) {
localStorage.setItem('token', resp.token)
this.setState({
user: resp.user,
token: resp.token
}, () => {
this.props.history.push("/dashboard")
})
}
else {
alert(resp.error)
}
}
componentDidMount(){
if (localStorage.getItem("token")) {
fetch('http://localhost:8000/current_user/', {
headers: {
Authorization: `Bearer ${localStorage.token}`
}
})
.then(r => r.json())
.then(this.handleResp)
}
}
handleRegister(newUser){
fetch( "http://127.0.0.1:8000/rest-auth/registration/", {
method: "POST",
headers: {
'content-type': "application/json"
},
body: JSON.stringify(newUser)
})
.then(res => res.json())
.then(this.handleResponse)
}
handleLogin(returningUser){
fetch('http://127.0.0.1:8000/rest-auth/login/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(returningUser)
})
.then(res => res.json())
.then(this.handleResponse)
}
renderRegisterForm = (routerProps) => {
if (routerProps.location.pathname === "/register") {
// debugger
return <Register formName="Register Form"
handleSubmit={this.handleRegister}
/>
}else if(routerProps.location.pathname === "/") {
return <HomePage formName="Log into Account"
handleSubmit={this.handleLogin}
/>
}
}
render() {
return (
<div>
{/* <Link to="/register">Sign Up</Link> */}
<Switch>
<Route exact path="/" render={this.renderRegisterForm} />
<Route exact path="/register" render={this.renderRegisterForm} />
<Route path="/dashboard" exact component={Dashboard} />
<Route render={ () => <p>Page not Found</p> } />
</Switch>
{/* <Link href="/register"
// onClick={this.handleRegisterLinkPage}
variant="body1">
{"Don't have an account? Sign Up"}
</Link> */}
</div>
);
}
}
export default withRouter(App);
import React,{Component}来自'React';
从“react Router dom”导入{Router,Switch,Route,withRouter,Link}
从“/components/HomePage”导入主页;
从“/组件/寄存器”导入寄存器
从“/components/Dashboard”导入仪表板
//从“@material ui/core/Link”导入链接;
//从“/images/7f76e8e7692375107e5998013155af0d.jpg”导入{background}”;
//导入{TravelerEffect、MosaicGroundEffect、OceanEffect、,
//雨效应、海波效应、降雪效应、降雪慢效应、,
//间距效应
//}来自“反应背景动画”
类应用程序扩展组件{
状态={
用户:{
电邮:“,
用户名:“”,
_是否处于活动状态:“”,
名字:“,
姓氏:“,
生物信息:“,
年龄:“,
出生地点:“,
学校:“,
职业:“,
你在网站上寻找什么,
配置文件图片:空,
登录者:“,
},
令牌:“”,
}
HandlerResponse(resp){
控制台日志(分别为用户);
如果(代表用户){
localStorage.setItem('token',resp.token)
这是我的国家({
用户:resp.user,
令牌:resp.token
}, () => {
this.props.history.push(“/dashboard”)
})
}
否则{
警报(相应错误)
}
}
componentDidMount(){
if(localStorage.getItem(“令牌”)){
取('http://localhost:8000/current_user/', {
标题:{
授权:`Bearer${localStorage.token}`
}
})
.then(r=>r.json())
.然后(这个.handleResp)
}
}
HandlerRegister(新用户){
取回(“http://127.0.0.1:8000/rest-授权/注册/“{
方法:“张贴”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(newUser)
})
.then(res=>res.json())
.然后(这个.HandlerResponse)
}
handleLogin(返回者){
取('http://127.0.0.1:8000/rest-auth/login/'{
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(returningUser)
})
.then(res=>res.json())
.然后(这个.HandlerResponse)
}
renderRegisterForm=(routerProps)=>{
if(routerProps.location.pathname==“/寄存器”){
//调试器
返回
}else if(routerProps.location.pathname==“/”){
返回
}
}
render(){
返回(
{/*注册*/}
找不到页面}/>
{/*
{“没有帐户?注册”}
*/}
);
}
}
使用路由器(App)导出默认值;
my HomePage.jsx(基本上是我的登录页面)
从“React”导入React;
从“react router dom”导入{Redirect}
从“@material ui/core/Avatar”导入化身;
从“@material ui/core/Button”导入按钮;
从“@material ui/core/CssBaseline”导入CssBaseline;
从“@material ui/core/TextField”导入TextField;
从“@material ui/core/FormControlLabel”导入FormControlLabel;
从“@material ui/core/Checkbox”导入复选框;
从“@material ui/core/Link”导入链接;
从“@material ui/core/Paper”导入纸张;
从“@material ui/core/Box”导入框;
从“@material ui/core/Grid”导入网格;
//从“@material ui/icons/LockOutlinedIcon”导入LockOutlinedIcon;
从“@material ui/core/Typography”导入排版;
从“@material ui/core/styles”导入{withStyles}”;
const useStyles=主题=>({
根目录:{
高度:“100vh”,
},
图片:{
背景图片:“url”(https://source.unsplash.com/random)',
背景重复:“不重复”,
背景颜色:
theme.palette.type=='light'?theme.palette.grey[50]:theme.palette.grey[900],
背景尺寸:'封面',
背景位置:"中锋",,
},
论文:{
边距:主题。间距(8,4),
显示:“flex”,
flexDirection:'列',
对齐项目:“居中”,
},
化身:{
边距:主题。间距(1),
背景色:theme.palete.secondary.main,
},
表格:{
宽度:“100%”,//修复IE 11问题。
marginTop:主题。间距(1),
},
提交:{
边距:主题。间距(3,0,2),
},
});
函数版权(){
返回(
{'Copyright}
你的网站
{' '}
{新日期().getFullYear()}
{'.'}
);
}
类。组件{
//HandlerRegisterLinkPage=(事件)=>{
//event.preventDefault()
//返回
import React from 'react';
import {Redirect} from "react-router-dom"
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Paper from '@material-ui/core/Paper';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
// import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
const useStyles = theme => ({
root: {
height: '100vh',
},
image: {
backgroundImage: 'url(https://source.unsplash.com/random)',
backgroundRepeat: 'no-repeat',
backgroundColor:
theme.palette.type === 'light' ? theme.palette.grey[50] : theme.palette.grey[900],
backgroundSize: 'cover',
backgroundPosition: 'center',
},
paper: {
margin: theme.spacing(8, 4),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
});
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{'Copyright © '}
<Link color="inherit" href="https://material-ui.com/">
Your Website
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}
class HomePage extends React.Component {
// handleRegisterLinkPage = (event) => {
// event.preventDefault()
// return<Redirect to={"/register"}/>
// // debugger
// }
render(){
const {classes} = this.props
return (
<Grid container component="main" className={classes.root}>
<CssBaseline />
<Grid item xs={false} sm={4} md={7} className={classes.image} />
<Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
{/* <LockOutlinedIcon /> */}
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
{/* <Link href="#" variant="body2">
Forgot password?
</Link> */}
</Grid>
<Grid item>
<Link href="/register"
// onClick={this.handleRegisterLinkPage}
variant="body1">
<Button> Don't have an account? Sign Up</Button>
</Link>{' '}
</Grid>
</Grid>
<Box mt={5}>
<Copyright />
</Box>
</form>
</div>
</Grid>
</Grid>
);
}
}
export default withStyles(useStyles)(HomePage)
import React, { useState, useEffect } from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import TextareaAutosize from '@material-ui/core/TextareaAutosize';
import { MuiPickersUtilsProvider, KeyboardDatePicker } from '@material-ui/pickers';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import DateFnsUtils from '@date-io/date-fns';
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{'Copyright © '}
<Link color="inherit" href="https://material-ui.com/">
Your Website
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(3),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function Register() {
const classes = useStyles();
const [email, setEmail] = useState(" ")
const [password, setPassword] = useState(" ")
const [confirmPassword, setConfirmPassword] = useState(" ")
const [username, setUsername] = useState(" ")
const [birthPlace, setBirthPlace] = useState(" ")
const [bio, setBio] = useState(" ")
const [school, setSchool] = useState(" ")
const [firstName, setFirstName] = useState(" ")
const [lastName, setLastName] = useState(" ")
const [occupation, setOccupation] = useState(" ")
const [what_are_you_seeking_on_site, setWhat_are_you_seeking_on_site] = useState("Friendship")
const [age, setAge] = useState(new Date('2014-08-18T21:11:54'));
const [errors, setErrors] = useState(" ")
// const [selectedDate, setSelectedDate] =
// const [value, setValue] = React.useState('Friendship');
useEffect(() => {
if (localStorage.getItem('token') !== null) {
window.location.replace('http://localhost:3000/dashboard');
} else {
window.location.replace('http://localhost:3000/')
}
}, []);
const handleSubmit = e => {
e.preventDefault();
const user = {
email: email,
username: username,
birthPlace: birthPlace,
bio: bio,
school: school,
age: age,
password: password,
confirmPassword: confirmPassword,
firstName: firstName,
lastName: lastName,
occupation: occupation,
what_are_you_seeking_on_site: what_are_you_seeking_on_site,
};
fetch('http://127.0.0.1:8000/rest-auth/registration/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then(data => {
if (data.key) {
localStorage.clear();
localStorage.setItem('token', data.key);
window.location.replace('http://localhost:3000/dashboard');
} else {
setEmail('');
setPassword('');
setConfirmPassword('');
localStorage.clear();
setErrors(true);
}
});
};
const handleChange = (event) => {
setWhat_are_you_seeking_on_site(event.target.value);
};
const handleDateChange = (date) => {
setAge(date);
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<form className={classes.form} onSubmit={handleSubmit} noValidate>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Grid item xs={12} sm={6}>
<TextField
autoComplete="username"
name="Username"
variant="outlined"
required
fullWidth
id="Username"
label="Username"
autoFocus
value={e => setUsername(e.target.value)}
/>
</Grid>
<TextField
autoComplete="fname"
name="firstName"
variant="outlined"
required
fullWidth
id="firstName"
label="First Name"
autoFocus
value={e => setFirstName(e.target.value)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
variant="outlined"
required
fullWidth
id="lastName"
label="Last Name"
name="lastName"
value={e => setLastName(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="email"
value={e => setEmail(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
value={e => setPassword(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="Confirm password"
label="Confirm Password"
type="password2"
id="password2"
value={e => setConfirmPassword(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextareaAutosize
aria-label="minimum height"
fullWidth
label="Bio"
rowsMin={3}
placeholder="Minimum 3 rows"
value={e => setBio(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="Birth Place"
label="Where were you born"
id="birthPlace"
value={e => setBirthPlace(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="School"
label="School"
id="School"
value={e => setSchool(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="Occupation"
label="Occupation"
id="Occupation"
value={e => setOccupation(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset">
<FormLabel component="legend">What are you here for</FormLabel>
<RadioGroup aria-label="what_are_you_seeking_on_site" name="what_are_you_seeking_on_site" value={what_are_you_seeking_on_site} onChange={handleChange}>
<FormControlLabel value="Dating" control={<Radio />} label="Dating" />
<FormControlLabel value="Friendship" control={<Radio />} label="Friendship" />
<FormControlLabel value="Networking" control={<Radio />} label="Networking" />
<FormControlLabel value="Business" control={<Radio />} label="Business" />
</RadioGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
margin="normal"
id="date-picker-dialog"
label="Date picker dialog"
format="MM/dd/yyyy"
// value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
value={e => setAge(e.target.value)}
/>
</MuiPickersUtilsProvider>
</Grid>
<Grid item xs={12}>
<FormControlLabel
control={<Checkbox value="allowExtraEmails" color="primary" />}
label="I want to receive inspiration, marketing promotions and updates via email."
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign Up
</Button>
<Grid container justify="flex-end">
<Grid item>
<Link href="/" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={5}>
<Copyright />
</Box>
</Container>
);
}
useEffect(() => {
if (localStorage.getItem('token') !== null) {
window.location.replace('http://localhost:3000/dashboard');
} else {
window.location.replace('http://localhost:3000/')
}
}, []);
useEffect(() => {
if (localStorage.getItem('token') !== null) {
window.location.replace('http://localhost:3000/dashboard');
}
}, []);