Svelte评论轮播组件点击按钮报错TypeError: $$invalidate(...) is not a function
解决
TypeError: $$invalidate(...) is not a function错误 嘿,这个错误的根源其实一眼就能看出来——你按钮点击事件里的语法写错啦!
问题出在哪?
你看这两行点击事件的代码:
on:click={() => (showntestimonial += 2)((showntestimonial = showntestimonial % 3))} on:click={() => (showntestimonial++)((showntestimonial = showntestimonial % 3))}
这种写法在JavaScript里会被解析成:先执行showntestimonial += 2(或者showntestimonial++)得到一个数字结果,然后试图把这个数字当成函数去调用后面括号里的showntestimonial = showntestimonial % 3。但数字根本不是函数啊,自然就抛出了$$invalidate(...) is not a function的错误($$invalidate是Svelte内部用来更新响应式变量的函数,这里因为语法错误导致调用逻辑乱掉了)。
至于为什么功能还能正常运行?因为不管怎样,showntestimonial += 2和showntestimonial = showntestimonial % 3这两个操作其实都执行了——只是中间多了一次无效的“函数调用”,浏览器报错但没阻断后续逻辑而已。
怎么修复?
你需要把两个变量操作正确地组合起来,有两种常用方式:
1. 用代码块分开写(可读性更好)
<!-- 左箭头按钮 --> <button class="arrowbox" on:click={() => { showntestimonial += 2; showntestimonial = showntestimonial % 3; }}> <i class="far fa-chevron-left" /> </button> <!-- 右箭头按钮 --> <button class="arrowbox" on:click={() => { showntestimonial++; showntestimonial = showntestimonial % 3; }}> <i class="far fa-chevron-right" /> </button>
2. 用逗号运算符写成一行(更简洁)
逗号运算符会依次执行每个表达式,最后返回最后一个表达式的结果,刚好适合这种场景:
<!-- 左箭头按钮 --> <button class="arrowbox" on:click={() => (showntestimonial += 2, showntestimonial = showntestimonial % 3)}> <i class="far fa-chevron-left" /> </button> <!-- 右箭头按钮 --> <button class="arrowbox" on:click={() => (showntestimonial++, showntestimonial = showntestimonial % 3)}> <i class="far fa-chevron-right" /> </button>
这样修改后,语法错误就消失了,功能也能正常运行~
内容的提问来源于stack exchange,提问作者Gh05d
相关产品推荐
相关产品推荐

