React JS错误:无效的尝试重构不可迭代的实例 [英] React JS Error: Invalid attempt to destructure non-iterable instance
问题描述
我有一个排序过滤器,它使用一个数组来填充选项.试图查看选项 value
等于数组中的文本,但标题中出现错误:
I have a sort filter that takes an array to populate the options. Trying to see the option value
equal to the text within the array but I get the error within the title:
Invalid attempt to destructure non-iterable instance
我需要将文本作为选项标签中的值传递,以便在用户更新过滤器时,正确的文本显示给用户选择的内容.
I need to pass the text as the value within the option tag so that when the user updates the filter, the correct text displays to the choice the user made.
这是我的代码:
function Sorting({by, order, rp}: SortingProps) {
const opts = [
['Price (low)', 'price', 'asc'],
['Price (high)', 'price', 'desc'],
['Discount (low)', 'discount', 'asc'],
['Discount (high)', 'discount', 'desc'],
['Most popular', 'arrival', 'latest'],
['Most recent', 'arrival', 'latest'],
];
const onChange = (i) => {
const [text, by, order] = opts[i];
refresh({so: {[by]: order}});
/* GA TRACKING */
ga('send', 'event', 'My Shop Sort By', text, 'Used');
};
return (
<div className={cn(shop.sorting, rp.sorting.fill && shop.sortingFill)}>
<Select className={shop.sortingSelect} label="Sort By" onChange={onChange} value={`${by}:${order}`}>
{opts.map(([text], i) =>
<Option key={i} value={text}>{text}</Option>
)}
</Select>
</div>
)
}
推荐答案
我几次导致此错误,因为每当我编写一个经常会做的 useState
钩子时,我就习惯于使用数组来进行解构,如下所示:
I caused this error a few times because whenever I write a useState
hook, which I would do often, I'm used to using an array to destructure like so:
const [ state, setState ] = useState();
但是我的自定义钩子通常会返回带有属性的对象:
But my custom hooks usually return an object with properties:
const { data, isLoading } = useMyCustomFetchApiHook();
有时候我不小心写了 [数据,isLoading]
而不是 {数据,isLoading}
,由于您要从数组中解构属性[],则当您要从其解构的对象是对象{}时.
Sometime I accidentally write [ data, isLoading ]
instead of { data, isLoading }
, which tiggers this message because you're asking to destructure properties from an array [], when the object you're destructuring from is an object {}.
这篇关于React JS错误:无效的尝试重构不可迭代的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!