React-Native 为什么会出现“不可迭代”

jus*_*227 2 javascript reactjs react-state

React / State / Arrays 的新手。

为什么会出现“不可迭代”

  const myVar = {
    '2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0}
  };
 
  const [myMarkedDates, setMarkedDates] = useState(myVar);
 
  const newVar = {
    '2022-12-17': {selected: true, textColor: 'red', activeOpacity: 0}
  };
  
  const newVars = [newVar, ...myMarkedDates];
 
  setMarkedDates(newVars);

Run Code Online (Sandbox Code Playgroud)

And*_*dré 5

您在这里将数组与对象混合在一起。使用展开符号...myMarkedDates返回对象的属性:

'2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0}
Run Code Online (Sandbox Code Playgroud)

这可以是另一个对象的属性,但不能是数组内的元素。

这对您来说是有效的语法:

const newVars = [newVar, {...myVar}];
Run Code Online (Sandbox Code Playgroud)

newVars是一个包含对象newVar和 的数组myVar

[
  {
    '2022-12-17': { selected: true, textColor: 'red', activeOpacity: 0 }
  },
  {
    '2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0 }
  }
]
Run Code Online (Sandbox Code Playgroud)

根据您想要实现的目标,这可能是首选:

const newVars = {...newVar, ...myVar};
Run Code Online (Sandbox Code Playgroud)

在上面的代码中将newVars是一个具有newVarmyVar属性组合的对象:

{
  '2022-12-17': { selected: true, textColor: 'red', activeOpacity: 0 },
  '2022-11-22': { selected: true, textColor: 'blue', activeOpacity: 0 }
}
Run Code Online (Sandbox Code Playgroud)