Shadcn RadioButton异常:React-hook-form值变更但UI未同步更新
解决Shadcn RadioGroup结合React-Hook-Form+Zustand时选中状态不实时更新的问题
问题根源
你的RadioGroup当前绑定的value是Zustand全局状态chosenAnswers[props.questionIndex],但用户选择选项时,只有React-Hook-Form的field值实时更新了,Zustand状态并没有同步变化,导致UI的选中指示器依然停留在之前保存的旧值上,只有点击保存按钮触发saveAnswer更新Zustand后才会切换。
解决方案
调整RadioGroup的value绑定逻辑,让它直接跟随React-Hook-Form的field值,同时按需实时同步到Zustand状态:
- 修改Controller与RadioGroup的绑定
<form onSubmit={handleSubmit(saveAnswer)}> <p className="my-4 text-lg">{props.question}</p> <Controller control={control} name="answer" // 用Zustand的已保存值作为form字段的初始值 defaultValue={chosenAnswers[props.questionIndex]} render={({ field }) => { return ( <RadioGroup // 绑定form的field.value,实时响应选中变化 value={field.value} onValueChange={(newValue) => { field.onChange(newValue); // 可选:如果需要实时同步到Zustand全局状态,在这里调用更新方法 // 示例:updateChosenAnswer是你Zustand store里定义的更新函数 updateChosenAnswer(props.questionIndex, newValue); }} > {choiceElements} </RadioGroup> ) }} /> <Button type="submit">save answer</Button> <DevTool control={control} /> </form>
- choiceElements代码保持不变
const choiceElements = props.choices.map(answerText => { return ( <div key={answerText}> <RadioGroupItem value={answerText} id={answerText} /> <Label htmlFor={answerText}>{answerText}</Label> </div> ) })
逻辑说明
- 实时UI更新:RadioGroup的value绑定
field.value后,用户选择选项时,React-Hook-Form的字段值会立即变化,驱动RadioGroup的选中状态实时更新。 - 初始值同步:通过
defaultValue将Zustand中已保存的答案作为form字段的初始值,确保组件加载时选中状态正确。 - 可选实时全局同步:如果需要选择时就把值同步到Zustand,直接在
onValueChange里调用全局状态的更新函数,无需等待提交按钮。
补充说明
如果你的saveAnswer函数原本是用来将form值同步到Zustand的,依然可以保留这个逻辑,作为最终提交的确认保存步骤,和实时同步互不冲突。
内容的提问来源于stack exchange,提问作者semi_92
相关产品推荐
相关产品推荐

