如何从AI流中直接、快速地更新字段状态?
我正在开发一个文本编辑器,编辑框的输入绑定到了一个react-hook-form的字段。我还在使用一个AI写作助手,它从后端实时流式传输文本,我需要在文本流入的过程中更新输入框。这是我尝试的做法:
const { setValue, getValues } = useFormContext();
const { output } = await generate(prompt);
for await (const delta of readStreamableValue(output)) {
if (delta) {
const value = getValues("editor");
setValue("editor", value + delta);
}
}
这在第一次更新时能起作用,大概到那时就停止再更新了。如果我把值输出到控制台,我确实看到它在变化,只是输入框没有随之更新。这是某种批处理问题吗?我原本以为react-hook-form在内部使用refs而不是state,所以更新state时不会遇到相同的批处理/生命周期问题。有什么办法能让它工作吗?
解决方案
你可以尝试在setState中使用一个本地累积变量来更新值
const { setValue } = useFormContext();
let accumulated = "";
for await (const delta of readStreamableValue(output)) {
if (!delta) continue;
accumulated += delta;
setValue("editor", accumulated, {
shouldDirty: true
});
}
同时使用这个 shouldDirty:true,它会让formContext识别出你表单中的脏字段。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。