在文本区域中键入少于5个字符时,我收到400个错误请求。并且当用户输入太短的文本消息时,我试图向他/她显示错误消息。但是消息不会显示出来。
const handleFormSubmit = (e) => {
e.preventDefault()
const options = {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ message: newThought })
}
fetch(HAPPY_THOUGHTS_URL, options)
.then(response => response.json())
.then((response => {
if (response.ok === false) {
setError('show')
} else {
fetchThoughtsList()
}
}))
.catch(error => console.error(error))
}
......
return (
<div>
{error === 'show' &&
<ErrorPopup
message="Oops, your message needs to be more than 4 characters. Please give it one more try!"
setError={setError}
/>
}
</div>
)发布于 2021-03-26 03:20:41
事件的顺序有一个问题,在你的第一个then中,你可以读取ok字段,但在第二个中,只有你调用json获得的数据。试试像这样的东西
fetch(HAPPY_THOUGHTS_URL, options)
.then(response => {
if (!response.ok) {
setError('show');
return null;
}
return response.json();
})
.then(response => {
if (response) {
fetchThoughtsList()
}
})
.catch(error => console.error(error))我假设您只是没有包括处理响应数据的部分,但是如果您真的什么都不做,那么就不需要response.json()和第二个then了
fetch(HAPPY_THOUGHTS_URL, options)
.then(response => {
if (response.ok) {
fetchThoughtsList()
}
else{
setError('show');
}
})
.catch(error => console.error(error))尝试将.then(response => {console.log('actual ok value',response.ok); return response}作为第一个then插入,看看它打印了什么,也许响应确实是ok
发布于 2021-03-26 23:40:48
fetch(API_URL, options)
.then(response => {
if (!response.ok) {
setError(true)
throw new Error ('Ups, something went wrong')
} else {
setNewThought('')
return response.json()
}
})
.then(recievedThought => setThoughtsList([recievedThought, ...thoughtsList]))
.catch(err => console.error(err))
} https://stackoverflow.com/questions/66805483
复制相似问题