You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Hooks useReducer路由跳转报错:buttonAction is not a function

解决React Hooks useReducer + Router 跳转时的 TypeError: buttonAction is not a function 问题

我一眼就抓住了问题的核心——你定义buttonAction的方式存在一个容易忽略的JavaScript语法坑:

buttonAction={e => state.length < 4 && dispatch({ type: "addDigit", payload: e }) }

在JS里,&&逻辑运算符的特性是:当左侧条件为false时,会直接返回左侧的布尔值(也就是false),而不是一个函数。这意味着当你的PIN码长度达到4位之后,buttonAction就从可调用函数变成了false。此时如果用户点击数字键,或者组件在路由跳转过程中还有未处理的点击事件待执行,就会触发TypeError: buttonAction is not a function。

而手动输入/LoggedInURL时,App组件会重新初始化,state是空字符串,state.length < 4为true,buttonAction是正常的函数,所以不会报错。

修复方案

把buttonAction改成始终返回函数的形式,用条件判断包裹dispatch逻辑,彻底避免布尔值代替函数的情况:

<KeyDigit 
  digit={v} 
  key={v} 
  className="keyDigit number" 
  buttonAction={(digit) => {
    if (state.length < 4) {
      dispatch({ type: "addDigit", payload: digit });
    }
  }} 
/>

这样不管PIN码长度是否达到4位,buttonAction都是一个有效的函数,点击时只会在条件满足时执行dispatch,再也不会出现"不是函数"的错误。

额外小建议

后续实现PIN校验逻辑时,建议在校验通过后再触发路由跳转,避免组件在状态更新的临界阶段出现异常。

内容的提问来源于stack exchange,提问作者Matthew Player

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:31:17