英文:
How to format error messages as list in React?
问题
const handleSubmit = (event) => {
event.preventDefault();
postWithoutAuth("/auth/signup", formValues)
.then((response) => {
setAlert("注册成功", "success");
})
.catch((error) => {
error.response.data.errors.forEach(e => {
setAlert(<li>{e.field + " " + e.message}</li>);
})
});
};
英文:
I return the following response from Spring Boot API and want to format properly on my React app:
Array(4)
0: {field: 'lastName', message: 'size must be between 3 and 50'}
1: {field: 'username', message: 'size must be between 3 and 20'}
2: {field: 'password', message: 'size must be between 6 and 100'}
3: {field: 'firstName', message: 'size must be between 3 and 50'}
I have the following alert method that displays messages. But I cannot format the message by including all the error messages by type:
const handleSubmit = (event) => {
event.preventDefault();
postWithoutAuth("/auth/signup", formValues)
.then((response) => {
setAlert("Signed up successfully", "success");
})
.catch((error) => {
error.response.data.errors.foreach(e => {
setAlert(<li>{e.field + " " + e.message}</li>);
})
});
};
Any idea?
答案1
得分: 0
1) 你在JS中,所以`<li>{e.field + " " + e.message}</li>` 需要变成 `"<li>" + e.field + " " + e.message + "</li>"`
2) 你连续触发了很多警告。
3) `forEach()`是区分大小写的。你写成了`foreach()`
4) 在`setAlert()`中缺少了`severity`
假设`error.response.data.errors`包含你问题中的数组,尝试以下代码:
.catch((error) => {
var alertContents = ''<ul>'';
error.response.data.errors.forEach(e => {
alertContents += ""<li>" + e.field + " " + e.message + "</li>\n"";
});
setAlert(alertContents + '</ul>', 'error');
});
英文:
Four things
- you are in JS so
<li>{e.field + " " + e.message}</li>
needs to be"<li>" + e.field + " " + e.message + "</li>"
- you are pumping a lot of alerts in quick succession.
forEach()
is case sensitive. You haveforeach()
- the
severity
onsetAlert()
is missing
Presuming that error.response.data.errors
contains the array in your question, try the following:
.catch((error) => {
var alertContents = '<ul>';
error.response.data.errors.forEach(e => {
alertContents += "<li>" + e.field + " " + e.message + "</li>\n";
});
setAlert(alertContents + </ul>, "error");
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论