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

为什么点击按钮触发Redux Action时会出现Invalid hook call错误

问题根因

你遇到的Invalid hook call错误核心原因是在addReview这个Redux异步action内部调用了React Hook(比如useSelector、useState、useDispatch等),action不属于函数组件,且你在点击事件回调中触发该action时,调用时机不在函数组件顶层,不符合Hook的调用规则。

修复方案

1. 修复异步action的Hook调用错误

如果需要在thunk异步action中获取Redux的状态数据,直接使用thunk提供的第二个参数getState即可,不要调用useSelector这类Hook,修正后的action写法参考:

import axios from "axios";

export const addReview = (productInfo) => async (dispatch, getState) => {
  // 示例:如果需要取redux中的数据,用getState,不要用useSelector
  // const userInfo = getState().userInfoReducer;
  try {
    await axios({
      method: "post",
      url: "替换为你的实际后端接口地址", // 你原有代码中url变量未定义,需要补全
      headers: { "Content-Type": "application/json" }, // 原有配置写错了,请求头字段是headers不是header
      data: {
        name: productInfo.name,
        rating: productInfo.rating,
        description: productInfo.description,
        buyAgain: productInfo.buyAgain,
        productId: productInfo.productId,
      },
    }).then((response) => {
      dispatch({
        type: "PRODUCTS_SUCCESS",
        payload: response.data,
      });
    });
  } catch (error) {
    dispatch({
      type: "PRODUCTS_FAILURE",
      payload: error,
    });
  }
};

2. 修复组件内普通变量的状态管理问题

你组件中存储用户公开名称的name是普通let变量,只要组件触发重新渲染(比如用户点击星级修改starRate),变量值就会被重置为undefined,需要改为React State管理:

// 原有let name; 删除,替换为state声明,默认值取localStorage的fName
const [name, setName] = useState(fName);

// 对应的名称输入框修改value和onChange逻辑
<input
  type="text"
  className="form-control review-product-profile-name"
  value={name}
  onChange={(e) => setName(e.target.value)}
/>

3. 优化商品查找逻辑

你原有使用map遍历数组找对应商品的写法性能差且不符合语义,改为find方法即可:

const productToDisplay = allProducts.find(product => product._id === currentProduct);
const title = productToDisplay?.title?.length > 60 ? `${productToDisplay.title.substring(0,60)}...` : productToDisplay?.title;

内容的提问来源于stack exchange,提问作者Tim Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:24:03