【发布时间】:2020-07-28 18:31:50
【问题描述】:
这里是 React 初学者,现在我正在尝试学习解构,并且一直在阅读它,例如:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
我知道的是,当你解构两边应该是相同的,比如如果你有数组,那么两边都应该是数组,但是在这里我开始工作,右侧是对象(?),左侧是数组(解构? ),我的问题是,如果您正在解构一个对象,那么您可以通过它的名称(双方应该具有相同的名称)和通过它的索引访问它,那么为什么在这段代码中它的工作方式不同呢?以及为什么您可以像这样访问这里的属性:const count = state.count?解构不应该解决这个问题吗?英语不是我的母语,如有错误请见谅。
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;
【问题讨论】:
-
您不是将
{ count: 4, theme: 'blue' }解构为一个数组,而是将函数调用useState({ count: 4, theme: 'blue' })的返回值 解构为一个数组。useState返回一个数组,所以它们确实匹配。 -
@BrianThompson 你能给我这个的javascript例子(没有useState),也许我会更好地理解它
-
但通常它甚至不必是一个数组。你可以像这样解构任何迭代。例如字符串
const [a, b] = 'ab'。 -
const [{ count, theme }, setState] = useState({ count: 4, theme: 'blue' })这是你要问的吗?
标签: javascript html reactjs function destructuring