简体   繁体   English

将 object 解构为数组?

[英]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:这里是 React 初学者,现在我正在尝试学习解构,并且一直在阅读有关它的示例:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 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?我所知道的是当你解构时两侧应该相同,就像如果你有数组那么两侧应该是数组,但在这里我开始工作,右侧是 object(?),左侧是数组(解构?),我的问题是如果你正在解构一个 object 那么你可以通过它的名字访问它(双方应该有相同的名字)和数组通过它的索引,那么为什么在这段代码中它的工作方式不同? and why you can access properties here like this: const count = state.count ?为什么你可以像这样访问属性: 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. useState是一个反应钩子,它接受初始值作为其参数并返回一个数组。

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但是在 Arrays 的情况下,解构变量可以有任何名称,是的,它将被解构为 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.useState反应挂钩的情况下, useState返回一个array ,其初始值是您在其第一个索引上传递的,并返回一个 function 以在其第二个索引上设置相同的值。

const [value,setValue] = useState(initialValue)

In your case, initial value is an object and you destructure an array which is returned by useState在你的例子中,初始值为 object 并且你解构了一个由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由于您的state是一个包含键counttheme的 object ,您可以通过点符号或括号符号访问它

You can further destructure your state object too like below您也可以像下面这样进一步解构您的state object

  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.看起来让您感到困惑的是您将 object 传递给useState ,但它返回一个数组。

To hopefully clarify, lets create a really simple example to substitute the useState function.为了澄清,让我们创建一个非常简单的示例来替换useState function。

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

As you can see, myFunction returns an array.如您所见, myFunction返回一个数组。 That array contains the object passed in, and the length of the object.该数组包含传入的 object,以及 object 的长度。

If we want to destructure this array, it would look very similar to the useState example:如果我们想解构这个数组,它看起来与useState示例非常相似:

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.乍一看,您似乎正在从 object 解构为一个数组,但我们知道myFunction返回一个数组。 So it is actually from an array to an array.所以实际上是从数组到数组。

useState works the same way. useState的工作方式相同。 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.上面是一块 state,名为state ,它以 object 开始, count属性值为4theme属性值为'blue' ,理论上这可以随时间变化。 setState is a setter function used to update your piece of state called state . setState是一个 setter function 用于更新你的 state 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.一种访问 state 和 setter 的奇特方法。

Array destructuring is a JavaScript feature, it is not something specific to React.数组解构是一个 JavaScript 特性,它不是 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.我想在这里澄清的第一件事是左边的方括号不创建数组,这里没有创建数组,而是将方括号分配给 JavaScript,他们说假设右边是什么等号的一边是一个数组,如果是,从那里取出第一个元素并将其分配给一个名为 firstElement 的全新变量,然后从数组中取出第二个元素并将其分配给一个名为 secondElement 的变量,就这样那是怎么回事。

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.所以这就是数组解构,它是一个小捷径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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