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

Chakra UI的useRadioGroup数据源未加载时如何设置defaultValue初始值

问题修复方案

核心原因

  1. 初始加载阶段empresas为空数组或未初始化,直接访问empresas[0].CODIGO会触发属性读取报错
  2. 代码中已经为useRadioGroup传入value: field.value进入受控模式,defaultValue本身不会生效,默认选中值需要同步到react-hook-form的受控字段中

修复逻辑

  • 给数组访问添加安全兜底逻辑,避免空数组/未初始化报错
  • 新增useEffect监听empresas加载状态,加载完成后自动将第一个条目赋值给表单字段
  • 统一值的类型,避免数字和字符串格式不一致导致选中状态不匹配

修复后完整代码

import { Stack, useRadioGroup, FormControl } from "@chakra-ui/react";
import { useContext, useEffect } from "react";
import { Control, useController } from "react-hook-form";
import { AuthContext } from "../../context/AuthContext";
import { SelectRadio } from "../SelectRadio";

interface RadioGroupProps {
  control: Control;
  name: string;
  isRequired?: boolean;
}

export function RadioGroup({ control, name, isRequired }: RadioGroupProps) {
  const { empresas } = useContext(AuthContext);
  const {
    field,
    formState: { errors }
  } = useController({
    control,
    name,
    rules: { required: { value: true, message: "Escolha uma empresa" } }
  });

  // 监听empresas加载状态,加载完成后自动设置默认选中第一条
  useEffect(() => {
    if (empresas?.length && !field.value) {
      field.onChange(empresas[0].CODIGO.toString())
    }
  }, [empresas, field])

  const { getRootProps, getRadioProps } = useRadioGroup({
    name,
    onChange: field.onChange,
    value: field.value,
    // 添加空值兜底,避免初始化报错
    defaultValue: empresas?.[0]?.CODIGO?.toString() ?? ''
  })

  const group = getRootProps();
  return (
    <FormControl isRequired={isRequired} isInvalid={!!errors[name]} mb={6}>
      <Stack {...group} spacing="4">
        {empresas.map((value) => {
          const radio = getRadioProps({ value: (value.CODIGO).toString() })
          return (
            <SelectRadio key={value.CODIGO}  {...radio}>
              {value.RAZAO}
            </SelectRadio>
          )
        })}
      </Stack>
    </FormControl>
  )
}

内容的提问来源于stack exchange,提问作者Jaymes Costa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:24:04