[英]How can I set all the key of an object state to empty array and change just one of them in React js
I'm creating sign up form with next.js and I'm handling errors with joi.js, After Fetching the data if there is error, I want if the error is in the name input I will pass it as value of the name key in the errors state and pass an empty string to the other keys (email and password), and same thing for other errors, I tried to do it but when there is no error, the keys in the errors state have always the past values.我正在使用 next.js 创建注册表单,我正在使用 joi.js 处理错误,如果有错误,在获取数据后,我想如果错误出现在名称输入中,我将把它作为名称键的值传递给错误 state 并将空字符串传递给其他键(电子邮件和密码),对于其他错误也是如此,我尝试这样做但是当没有错误时,错误 state 中的键始终具有过去的值。
(Sorry for my bad English) (对不起,我的英语不好)
File where I fetch data Login.tsx我从中获取数据的文件Login.tsx
export default function Login() { const [data, setData] = useState({ name: "", email: "", password: "" }); const [errors, setErrors] = useState({ name: "", email: "", password: "", }); const handleChange = (e) => { setData({...data, [e.target.name]: e.target.value, }); }; const handleSubmit = async (e) => { e.preventDefault(); const res = await fetch("/api/users", { body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, method: "POST", }, { cache: 'no-store' }); const content = await res.json(); if(content.error) { setErrors({...errors, [content.error[0].path[0]]:content.error[0].message}) } console.log(errors); };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
There will always be the old values in the errors
state variable since you're setting the new error by spreading the old ones first: setErrors({...errors, *****})
errors
state 变量中总会有旧值,因为您通过首先传播旧值来设置新错误: setErrors({...errors, *****})
What does your content.error
contain?你的content.error
包含什么? I can see you're only accessing the first element ( content.error[0]
), but do you receive all errors for that submission?我可以看到您只访问了第一个元素 ( content.error[0]
),但是您是否收到了该提交的所有错误? If you do, you don't need to spread the old errors, just run through all of the reported errors from the response and recreate your errors
object.如果这样做,则不需要传播旧错误,只需运行响应中报告的所有错误并重新创建errors
object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.