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

React基于networkProductId调用fetch API时参数为空无法获取正确响应

问题根因
  • 你写的useEffect依赖数组为空,仅会在组件首次挂载时执行一次。如果networkProductId是父组件异步获取后传入props的,首次挂载时该值还未完成赋值,就是空值,且后续该值更新后也不会触发重新请求。
  • 函数fetchAPIDetails的形参与外层作用域的networkProductId变量重名,容易引发作用域取值混淆,建议优化。
修复方案
  • 将networkProductId添加到useEffect的依赖数组中,保证每次该值更新都会自动重新发起接口请求
  • 增加空值校验逻辑,避免networkProductId为空时发起无效请求
  • 修改fetchAPIDetails的形参名,避免和外层变量重名引发的作用域问题
修复后参考代码
function NetworkProductInfo(props) {
  const { networkProductId } = props.state;
  const [apiDataAccountList, setApiDataAccountList] = useState({});

  // 把networkProductId加入依赖数组
  useEffect(() => {
    // 空值判断,避免无效请求
    if (networkProductId) {
      fetchAPIDetails(networkProductId)
    }
  }, [networkProductId])

  // 修改形参名避免作用域冲突
  async function fetchAPIDetails(productId) {
    const response = await networkProductsService.getNetworkProductById(productId);
    setApiDataAccountList(response.data)
  };

  return (
    <>
      <Grid className={"text-field"}>
        <TextField
          label={
            <span>
              Client ID <span className={"label-required"}>*</span>
            </span>
          }
          variant="outlined"
          className={"field"}
          size="small"
          id="clientId"
          path={clientId.path}
          value={clientId.value}
          helperText={clientId.errorMsg}
          error={!!clientId.errorMsg}
          onChange={(e) => {
            onFieldChange(clientId.path, e.target.value);
            fetchAccountDetails(e.target.value);
          }}
          onBlur={() => {
            if (networkProductId) {
              fetchAPIDetails(networkProductId);
            }
          }}
        />
      </Grid>
      <ProductIdAccountList {...props} />
    </>
  )
}

内容的提问来源于stack exchange,提问作者Rashmi UI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:54:05