React JS 错误:解构不可迭代实例的尝试无效

新手上路,请多包涵

我有一个排序过滤器,它需要一个数组来填充选项。试图查看选项 value 等于数组中的文本,但标题中出现错误:

 Invalid attempt to destructure non-iterable instance

我需要将文本作为选项标签中的值传递,以便当用户更新过滤器时,正确的文本会显示给用户所做的选择。

这是我的代码:

 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>
    )
}

原文由 Filth 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 700
1 个回答

我造成了这个错误几次,因为每当我写一个 useState 钩子时,我经常这样做,我习惯于使用数组来解构,如下所示:

 const [ state, setState ] = useState();

但是我的自定义挂钩通常会返回一个具有以下属性的对象:

 const { data, isLoading } = useMyCustomFetchApiHook();

有时我不小心写了 [ data, isLoading ] 而不是 { data, isLoading } ,这触发了这条消息,因为你要求从数组 [] 中解构属性,而你从中解构的对象是一个对象{}。

原文由 conor909 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进