无法使用从Axios接收的数据在React Hooks中设置状态



我正在使用React Hooks创建一个登录表单,并使用Axios查询后端。成功登录后,我将重定向到正在工作的主页。问题是尝试不成功,我想将loginFailed设置为true,并在此基础上对表单进行条件呈现但不幸的是,setLoginFailed不起作用

这就是我在客户端所做的:

import React, { useState } from "react"
import { useForm } from "react-hook-form"
import { useHistory } from "react-router-dom";
import { yupResolver } from '@hookform/resolvers'
import * as yup from "yup"
import axios from 'axios'
import './Login.css'
const schema = yup.object().shape({
username: yup.string().required("Please enter Username."),
password: yup.string().required("Please enter Password.")
})
export default function Login() {
const [loginFailed, setLoginFailed] = useState(null);
const { register, handleSubmit, errors } = useForm({
resolver: yupResolver(schema)
})
const history = useHistory();
const onSubmit = data => {
axios.post('/login', data)
.then((response) => {
if (response.data.success) {
history.push("/")
} else {
setLoginFailed(true)
}
})
}
return (

<form className="login-form" onSubmit={handleSubmit(onSubmit)}>

{loginFailed && <p>Invalid Username/Password.</p>}
<input type="text" name="mobile" placeholder="Mobile Number" ref={register} />
<p className="error">{errors.mobile?.message}</p>

<input type="password" name="password" placeholder="Password" ref={register} />
<p className="error">{errors.password?.message}</p>

<input type="submit" value="Login" />
</form>
)
}

在服务器端:

var express = require('express')
var router = express.Router()
var passport = require('passport')
var Farmer = require('../models/farmer')

router.post('/login', function(req, res, next) {
console.log(req.body)
passport.authenticate('local', function(err, user, info) {
if (err) { 
return res.json({success: false}) 
}
if (!user) { 
return res.json({success: false}) 
}
req.logIn(user, function(err) {
if (err) { 
return res.json({success: false}) 
}
return res.json({success: true})
})
})(req, res, next)
})
module.exports = router

我做错了什么?如何在客户端正确设置我的状态?

我在本地重新创建了您的应用程序,除了您用于";"移动号码";输入在yup模式中,您有username,而输入的名称是mobile。所以你必须把其中一个换成另一个。

在我的示例中,这意味着yup不认为提交有效,并且从未向API提交任何内容。除非问题中的代码与实际代码不同,否则onSubmit不应该发生。我很好奇你的代码是如何进入axios.then的。

无论如何,这里有一个工作示例:

App.js:

import React, { useState } from "react"
import { useForm } from "react-hook-form"
import { useHistory } from "react-router-dom";
import { yupResolver } from '@hookform/resolvers'
import * as yup from "yup"
import axios from 'axios'
const schema = yup.object().shape({
username: yup.string().required("Please enter Username."),
password: yup.string().required("Please enter Password.")
})
export default function Login() {
const [loginFailed, setLoginFailed] = useState(false);
const { register, handleSubmit, errors } = useForm({
resolver: yupResolver(schema)
})
const history = useHistory();
const onSubmit = data => {
axios.post('http://0.0.0.0:5000/login', data)
.then((response) => {
if (response.data.success) {
history.push("/")
} else {
setLoginFailed(true)
}
})
.catch(console.log)
}
return (

<form className="login-form" onSubmit={handleSubmit(onSubmit)}>

{loginFailed && <p>Invalid Username/Password.</p>}
<input type="text" name="username" placeholder="Mobile Number" ref={register} />
<p className="error">{errors.mobile?.message}</p>

<input type="password" name="password" placeholder="Password" ref={register} />
<p className="error">{errors.password?.message}</p>

<input type="submit" value="Login" />
</form>
)
}

server.js:

const cors = require('cors')
var express = require('express')
var router = express.Router()

router.post('/login', function(req, res, next) {
return res.json({ success: false })
})
var app = express()
app.use(cors())
app.options('*', cors())
app.use('/', router)
app.listen(5000, () => {
console.log(`Example app listening at http://localhost:${5000}`)
})

注意,我在axios.post中添加了catch来处理错误,没有重新创建passport内容,只是返回{success: false}来测试代码。此外,正如注释中所提到的,最好使用false而不是null初始化布尔状态。

问题在于使用表单标记。

您需要将您的表单提交操作修改为

const handleFormSubmit = (e) => {
e.preventDefault();
handleSubmit(onSubmit);
}
<form className="login-form" onSubmit={(e) => handleFormSubmit(e)}>
...
...
</form>

默认情况下,在表单提交操作中,它会触发一个重新加载操作,从而导致您的问题。

相关内容

  • 没有找到相关文章

最新更新