React Typescript登录不发送请求,但重新呈现主要组件

时间:2019-10-16 15:08:53

标签: javascript reactjs typescript react-router axios

我的反应有问题。当我按下登录按钮后,来自按钮附加功能的axios调用有时会将请求发送到后端(经过测试以查看春季是否有问题,但对于邮递员,每次都可以正常运行),但是当从前端发送,并不总是到达后端。此外,它在前面重新呈现并在URL中显示引入的名称和密码。 有什么想法吗?另外,如果我坚持一段时间,它将神奇地更改前端的url,并在后端正确显示。我在诺言中有一个突破点,但从未实现。 下面是我的前端App.tsx,Login.tsx和Doctor.tsx。

Login.tsx

import React from 'react';
import './App.css';
import Login from './components/Login';
import CssBaseline from "@material-ui/core/CssBaseline";
import {Route, Switch} from "react-router";
import DoctorMainPage from './components/Doctor';
import {BrowserRouter} from "react-router-dom";


const App: React.FC = () => {
  return (
          <>
                  <BrowserRouter>
                      <Switch>
                          <Route exact path = "/" component={Login}/>
                          <Route exact path = "/doctor" component={DoctorMainPage}/>
                      </Switch>
                  </BrowserRouter>
          </>

  );
};

export default App;
Login.tsx

import React, {useEffect, useState} from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
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 {Paper} from "@material-ui/core";
import useRouter from "use-react-router";
import appState from "../store/state";
import actions from "../actions/actions";
import axios from 'axios';
import {observer} from "mobx-react";


const useStyles = makeStyles(theme => ({
    '@global': {
        body: {
            backgroundColor: theme.palette.common.white,
        },
    },
    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(1),
    },
    submit: {
        margin: theme.spacing(3, 0, 2)
    },
}));

const SignIn = (function SignIn() {

    useEffect(() =>
        {
            setPassword("");
            setUsername("");
        },
        []
    );

    debugger;
    const login = () => {
        debugger;
      axios.post("http://localhost:8080/login", {
          username: username,
          password: password
      }).then((response) => {
          debugger;
          console.log(response.data);
          history.push("/doctor");
      });
    };

    const {history, location, match} = useRouter();
    const classes = useStyles();
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const isValid = () => {
        return username.length > 0 && password.length > 0
    };
    return (
        <>


            <Container component="main" maxWidth="xs">

                <Paper className={classes.paper}>
                    <Avatar className={classes.avatar}>
                        <LockOutlinedIcon />
                    </Avatar>
                    <Typography component="h1" variant="h5">
                        Sign in
                    </Typography>
                    <form className={classes.form} noValidate>
                        <TextField onChange={(e) => setUsername(e.target.value)}
                                   variant="outlined"
                                   margin="normal"
                                   required
                                   fullWidth
                                   id="username"
                                   label="Username"
                                   name="username"
                                   autoComplete="username"
                                   autoFocus
                        />
                        <TextField onChange={(e) => setPassword(e.target.value)}
                                   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 disabled={!isValid()} onClick={() => login()}
                                type="submit"
                                fullWidth
                                variant="contained"
                                color="primary"
                                className={classes.submit}
                        >
                            Sign In
                        </Button>
                    </form>
                </Paper>
            </Container>

        </>

    );
});

export default SignIn;
Doctor.tsx


import AppBarWithMenu from './AppBarWithMenu';
import {Paper} from "@material-ui/core";
import * as React from "react";
import PacientsTable from './Table';
import appState from "../store/state";
import {observer} from "mobx-react";
import Button from "@material-ui/core/Button";
import useRouter from "use-react-router";
import {useEffect} from "react";
import useReactRouter from 'use-react-router';

const DoctorMainPage = observer(function DoctorMainPage(){

    const {history, location, match} = useReactRouter();

    return (
        <Paper>
            <AppBarWithMenu/>
            <PacientsTable/>
            <Button onClick={() => history.push("/")}>
                Logout
            </Button>
        </Paper>
    );
});

export default DoctorMainPage;

GitHub

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为提交了 For RowNum = 7 To Sheet1.Cells(Sheet1.Rows.Count, "B").End(xlUp).Row If VBA.Format((Sheet1.Cells(RowNum, "H").Value), "DDMM") = VBA.Format((Sheet1.Range("B1").Value), "DDMM") Then Set OutApp = CreateObject("Outlook.Application") OutApp.Session.Logon Set OutMail = OutApp.CreateItem(0) With OutMail .SentOnBehalfOfName = Sheet1.Range("B3").Value .CC = Sheet1.Range("B4").Value .To = Sheet1.Cells(RowNum, "I").Value .Subject = "Happy Birthday !" .Body = "Happy Birthday" .Display .Send End With End If Next RowNum Sheet1.Range("B1").Value = Format(VBA.DateValue(Sheet1.Range("b1").Value) + 1, "dd-mm") 文件中定义的表单。

HTML表单是在Web应用程序中触发请求的另一种较旧的方法。与AJAX调用(例如您尝试使用axios进行的调用)不同,表单提交会导致浏览器加载新页面,因此所有JS上下文都会丢失。

HTML表单具有一个Login.tsx(这是执行请求的URL)和一个action(这是用于执行请求的HTTP方法)。 method默认是当前URL,而action默认是method(也可以是GET)。

这些表格可用于与请求一起发送数据。这些值取自POST标记内的输入字段。提交form表单后,数据通过URL参数发送。每个参数名称均来自每个包含的输入字段的GET属性。

所有这些说明了为什么您的应用程序单击按钮时会重新加载页面的原因,因为表单已提交,导致/ URL上有GET请求,URL中带有用户名和密码参数。 name事件永远不会触发,因此onClick函数不会被调用,因为页面正在重新加载(因此JS上下文消失了)。

为防止这种情况,只需将按钮类型从login更改为submit或对button事件中收到的事件对象进行preventDefault调用。