[英]Getting error as 'Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method'
In a React project, when I try to assign a constant to array object using spread operator, the above error is displayed.在 React 项目中,当我尝试使用扩展运算符将常量分配给数组对象时,会显示上述错误。 What are the required changes to be made in order to avoid the errors?
为了避免错误,需要进行哪些更改? I have gone through similar errors but, none are useful.
我经历过类似的错误,但没有一个是有用的。
Following is the code for reference以下是代码供参考
const newData = [
{
id: 123,
name: "Vijay"
},
{
id: 345,
name: "Sanket"
},
{
id: 546,
name: "Hitesh"
},
{
id: 789,
name: "Sameer"
},
{
id: 421,
name: "Akshay"
}
];
const updatedData = newData.map((data) => {
return {
...data,
disabled: false
};
});
const [data, setData] = React.useState(updatedData);
const [option1, setOption1] = React.useState();
const [option2, setOption2] = React.useState();
const onChangeHandler1 = (key, val) => {
console.log("VAL", val, "KEY");
const updating = [...data]; //Here the error persists
data.map((d, i) => {
if (d.id === val.value) {
updating[i] = {
...d,
disabled: true
};
}
if (option1) {
if (d.id === option1) {
updating[i] = {
...d,
disabled: false
};
}
}
});
setOption1(val.value);
setData(updating);
};
const onChangeHandler2 = (key, val) => {
console.log("VAL", val, "KEY", key);
const updating = [...data]; //Same error persists here too
data.map((d, i) => {
if (d.id === val.value) {
updating[i] = {
...d,
disabled: true
};
}
if (option2) {
if (d.id === option2) {
updating[i] = {
...d,
disabled: false
};
}
}
});
setOption2(val.value);
setData(updating);
};
return (
<>
<h2>Data 1</h2>
<Select
onChange={(key, val) => onChangeHandler1(key, val)}
placeholder="Select any one"
style={{ width: 120 }}
options={data
.filter((d) => d.disabled === false)
.map((_) => {
// console.log(_)
return {
value: _.id,
label: _.name
};
})}
bordered={false}
/>
<br />
<h2>Data 2</h2>
<Select
onChange={(key, val) => onChangeHandler2(key, val)}
placeholder="Select any one"
style={{ width: 120 }}
options={data
.filter((d) => d.disabled === false)
.map((_) => {
// console.log(_)
return {
value: _.id,
label: _.name
};
})}
bordered={false}
/>
</>
);
};
As seen above the error triggers at line const updating = [...data]
, when any option is selected.如上所述,在选择任何选项时,在Line
const updating = [...data]
时触发。 What is the best optimal solution?最佳最优解是什么? Please not here 'antd' library is used for design framework.
请不要在这里使用“antd”库来设计框架。
make this line const updating = [...data]
as this const updating = data
.将此行
const updating = [...data]
设为const updating = data
。 Hope your problem will be solved希望你的问题能得到解决
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.