根据其他问题和答案,我尝试了很多建议,但我不知道为什么我的表格不起作用。
我正在发送表单提交操作,但无法在const login
函数中获取值
有人可以指导如何解决这个问题吗?
Login.js
组件:
import React, { useState, useEffect, useCallback, useContext } from 'react'
import { Button, Grid, TextField } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles';
import { AuthContext } from 'contexts/auth'
function Login() {
const { login } = useContext(AuthContext)
return (
<Container>
<Grid container justify='center' spacing={4}>
<Grid item xs={12} container justify='center'>
</Grid>
<Grid item xs={12} container justify='center'>
<form onSubmit={login} >
<TextField
label='User'
name='username'
margin="normal"
/>
<TextField
label='Pass'
name='password'
type="password"
margin="normal"
/>
<Button
variant="outlined"
size="small"
color="primary"
type="submit">
Entrar
</Button>
</form>
</Grid>
</Grid>
</Container>
)}
export default Login
Auth.js
是我处理表单以及接收表单值的地方。 console.log
没有打印任何内容,并且出现此错误
TypeError:将圆形结构转换为JSON
auth.js
组件:
import React, { createContext, useCallback } from 'react'
export const AuthContext = createContext()
function Auth({ children }) {
const login = e => {
e.preventDefault();
console.log(e.target) //it doesn't print anything
fetch('http://localhost:4000/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: e.target.elements.password,
password: e.target.elements.password,
})
})
.then(response => {
if (response.ok) {
return response.text()
} else {
console.log('erro')
throw new Error('Error message')
}
})
}
return (
<AuthContext.Provider value={{login}}>
{children}
</AuthContext.Provider>
)
}
export default Auth