简体   繁体   中英

destructuring object to an array?

React beginner here, for now I'm trying to learn destructuring and have been reading about it for example here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

What I know is when you destructure both sides should be same, like if you have array then both sides should be array, but here i got working where in right side is object (?) and left side is array (destructuring?), my question is if you are destructuring an object then you can access it by its name (both sides should have same name) and array by its index, so why in this code its working differently? and why you can access properties here like this: const count = state.count ? shouldn't destructuring solve this? English is not my mother language, sorry for mistakes.

import React, { useState } from 'react';
import './App.css';

function App() {
  const [state, setState] = useState({ count: 4, theme: 'blue' });
  const count = state.count;
  const theme = state.theme;

  function decrementCount() {
    setState(prevState => {
      return { ...prevState, count: prevState.count - 1 }
    })
  }

  function incrementCount() {
    setState(prevState => {
      return { ...prevState, count: prevState.count + 1 }
    })
  }

  return (
    <>
      <button onClick={decrementCount}>- </button>
      <span>{count} </span>
      <span>{theme} </span>
      <button onClick={incrementCount}>+ </button>
    </>
  )
}

export default App;

useState is a react hook which accepts initial value as its parameter and return an array.

You are right that while destructuring, both side keys must be same but it is valid only for objects.

For example

let object = {
 foo:1,
 bar:2
}

const {foo,bar} = object

But in case of Arrays, destructuring variables can have any name, and yes it will be destructured with respec

For example

let array = [1,2,3,4]

const [one,two, , four] = array;

In case of useState react hook, useState returns an array with initial value you passed on its first index and a function to set the same on its second index.

const [value,setValue] = useState(initialValue)

In your case, initial value is an object and you destructure an array which is returned by useState

const [state, setState] = useState({ count: 4, theme: 'blue' }) // state is an object

Since your state is an object which contains keys count and theme , you can access it via dot notation or bracket notation

You can further destructure your state object too like below

  const [state, setState] = useState({ count: 4, theme: 'blue' });
  const { count, theme } = state

It appears that what is confusing you is that you pass an object to useState , but it returns an array.

To hopefully clarify, lets create a really simple example to substitute the useState function.

function myFunction(obj) {
  const length = Object.keys(obj).length;
  
  return [obj, length];
}

As you can see, myFunction returns an array. That array contains the object passed in, and the length of the object.

If we want to destructure this array, it would look very similar to the useState example:

const [obj, length] = myFunction({ foo: 'bar' });

At first glance it may appear that you're destructuring from an object to an array, but we know that myFunction returns an array. So it is actually from an array to an array.

useState works the same way. It just also manages stateful data for us so it seems more complicated to use.

const [state, setState] = useState({ count: 4, theme: 'blue' });

The above is a piece of state called state and it starts with an object with the property of count with a value of 4 and theme with a value of 'blue' and in theory this can change over time. setState is a setter function used to update your piece of state called state .

Together inside those square brackets, it's called array destructuring. A fancy way to get access to the piece of state plus the setter.

Array destructuring is a JavaScript feature, it is not something specific to React. You need to see more examples of these to understand them.

 function makeArray() { return [1, 10, 32, 40]; } const myArray = makeArray(); const firstElement = myArray[0]; const secondElement = myArray[1]; console.log(firstElement, secondElement);

The code snippet above is the equivalent and will get the exact same result as if I did this:

const [firstElement, secondElement] = makeArray();
console.log(firstElement, secondElement);

The first thing I want to clarify here is that the square brackets on the left hand side do not create an array, no array is being made here, instead the square brackets are assigned to JavaScript, they say assume that whatever is on the right hand side of the equal sign is an array, if it is, take the first element out of there and assign it to a brand new variable called firstElement then take the second element out of the array and assign it to a variable called secondElement, that's all that's going on.

We are simultaneously creating the array, creating two new variables and then assigning some elements from the array into those variables. So that syntax is just a short cut to write this exact same code. So that's what array destructuring is, it's a little shortcut.

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