简体   繁体   中英

How to use useState properly in this example?

I have the following code:

const [data, setData] = useState({
        name: '',
        surname: '',
        email: '',
        password: ''   
    });

However, I need to have something like:

 const [name, setName] = useState('');
 const [surname, setSurname] = useState('');
 const [email, setEmail] = useState('');
 const [password, setPassword] = useState('');

but still keeping the setData() function, as it is used.

You can add a function which will accept all of your parameters and uses your defined useState methods.

This way you can customize and check for the value of the parameters too.

So it would be like below:

function Example() {
    const [name, setName] = useState('');
    const [surname, setSurname] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    function changeData({name, surname, email, password}){
        // call your setSates here
        setName(name)
        setName(surname)
        setName(email)
        setName(password)
    }

}

Notice that if you want to check the parameters to be passed you have to check them not to be undefined . If you don't check that it will set the variables to undefined

you can use setData to update individual properties.

const [data, setData] = useState({
    name: '',
    surname: '',
    email: '',
    password: ''   
});

const setValue = (fieldName, value) => setData({...data, [fieldName]: value});

// to update name
setValue("name", "bob");

If I am understanding correctly, what you're looking for is a solution like the following:

function MyComponent(props) {
  const [data, setData] = React.useState({
    name: '',
    surname: ''
  })

  // will use `useEffect` as an example with an API call
  React.useEffect(() => {
    SomeAPICall()
      .then((data) => {
        setData({ 
          ...data, 
          name: data.name
        })
      })
  })
}

When calling setState , you need to copy the current state and update the property/properties that you want.


Alternatively, you could use React.useReducer to accomplish the same thing:

function MyComponent(props) {
  const [state, setState] = React.useReducer((p, n) => ({ ...p, ...n }), {
    name: '',
    surname: ''
  });

  // will use `useEffect` as an example with an API call
  React.useEffect(() => {
    SomeAPICall().then((data) => {
      setState({ 
        ...state, 
        name: data.name
      })
    })
  })
}

Similarly, you need to take the old state and update it with new values, then pass it to setState .


The spread syntax copies properties of an existing object onto a new object. Here's some reference if you're not familiar with this approach:

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