简体   繁体   中英

How to set properties to a object within a react hook?

Like the title says, how can I change state for only the object i want to and not both?

  const [state, setState] = useState([
    { foo1: null, foo2: "" },
  ]);

  function setfoo1(e) {
    e.preventDefault();
    // How do i set foo1: "Hello World"
  }

You can use spread operator to copy all field values you want to leave untouched like this:

setState({...state, foo1: 'Hello World'});

Spread the previous state and then assign foo1 last. eg

setState({
  ...state,
  foo1: "Hello World"
})

While other answers are valid approaches and will solve the problem they leave me wondering a few things. Why use one state object with many properties? useState will work with several. Your component's variables, foo1 and foo2, are the state of that component. Why drag out the code for change this state? Also, why not let react manage your state object for you?

const [foo1, setFoo1] = useState(null);
const [foo2, setFoo2] = useState("");

// .. later foo1 changes
setFoo1("Hello world"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM