[英]fetch send the data but doesn't go in then, React
I have problem with fetch.我在获取时遇到问题。 The data have been send, but doesn't do in then or catch, so I don't get if response is send ot not, only when I go in database.数据已发送,但在 then 或 catch 中没有做,所以我不知道是否响应是 send ot not,只有当我在数据库中的 go 时。 That is the code:那是代码:
import React, { useState } from 'react'
// import styles from './index.module.css'
import Input from '../input'
import SignUpButton from '../sign-up-button'
const SignUpForm = () => {
const [username, setUsername] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const handleSubmit = (e) => {
e.preventDefault()
let data = { username: username, email: email, password: password }
const headers = new Headers()
headers.append('Content-Type', 'application/json')
const options = {
method: 'POST',
headers: headers,
mode: 'cors',
cache: 'default',
body: JSON.stringify(data)
}
const request = new Request(`http://localhost:5000/user/sign-up`, options)
fetch(request)
.then(res => {
setUsername('')
setEmail('')
setPassword('')
})
.catch(e => {
console.log(e)
})
}
return (
<form onSubmit={handleSubmit}>
<Input
onChange={e => setUsername(e.target.value)}
label='Username:'
name='username'
placeholder='marolio'
value={username}
/>
<Input
onChange={e => setEmail(e.target.value)}
label='Email:'
name='email'
placeholder='marolio@yahoo.com'
value={email}
/>
<Input
onChange={e => setPassword(e.target.value)}
label='Password:'
name='password'
value={password}
/>
<SignUpButton
text='CREATE ACCOUNT'
btnStyle='submit'
/>
</form>
)
}
export default SignUpForm
Same structire worked for me in other project, so maybe something is changed but I don't know it.同样的结构在其他项目中对我有用,所以也许有些东西发生了变化,但我不知道。 Every help will be useful.每一个帮助都将是有用的。 Thanks!谢谢!
I made this change and it work, but I'm still curious why then and catch doesn't worked.我做了这个改变并且它起作用了,但我仍然很好奇为什么然后 catch 不起作用。
const response = fetch(request)
if(response){
setUsername('')
setEmail('')
setPassword('')
} else{
console.log('error')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.