[英]Change the value of all the fields in an object using useState hook
import { useState } from "react"; function useForm(initialfields) { const [value, setValue] = useState(initialfields); const reset = () => Object.keys(value).forEach((param) => setValue({ ...value, [param]: "" })); //setValue(Object.keys(value).forEach((val) => (value[val] = ""))); return [value, handleChange, reset]; } export default useForm;
I am trying to reset the value of all the fields in the object using setState.我正在尝试使用 setState 重置对象中所有字段的值。 However, the following code only resets the value in the last field.但是,以下代码仅重置最后一个字段中的值。 Let's say Value = {username:"Sam123",name:"Sam"}, then my current code is returning {username:"Sam123",name:""} instead of {username:"",name:""} [1]: https://i.stack.imgur.com/urdmM.png假设 Value = {username:"Sam123",name:"Sam"},那么我当前的代码返回 {username:"Sam123",name:""} 而不是 {username:"",name:""} [ 1]: https ://i.stack.imgur.com/urdmM.png
You are updating a state value using its previous value.您正在使用之前的值更新状态值。 You need to use the callback argument of the state setter.您需要使用状态设置器的回调参数。 https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
Also instead of calling the state setter ( setValue
) for each key, iterate inside the state setter callback.此外,不要为每个键调用状态设置器 ( setValue
),而是在状态设置器回调中进行迭代。 This causes the state setter to be called only once.这导致状态设置器只被调用一次。
function reset() {
setValue((value)=>{ // use previous value of value
return Object.keys(value).reduce((acc,key)=>{
acc[key] = ''; // set each key to empty string
return acc;
}, {});
});
}
I think you might just be overcomplicating it just a little bit.我想你可能只是稍微复杂了一点。
Instead of using the setValue
function and expanding the array to feed into it, the forEach
method is already doing the iteration over each key/value pair. forEach
方法已经在对每个键/值对进行迭代,而不是使用setValue
函数并扩展数组以将其输入。 It's like you're trying to do double work.这就像你在尝试做双重工作。
Instead of this: Object.keys(value).forEach((param) => setValue({ ...value, [param]: "" }));
取而代之的是: Object.keys(value).forEach((param) => setValue({ ...value, [param]: "" }));
See below:见下文:
let obj = {"username":"Sam123","name":"Sam"}; console.log( obj ); Object.keys(obj).forEach(key => obj[key] = "" ); console.log( obj );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.