在 NextJs 中,我想创建一个显示表单的组件,并通过数据库中的值填充此表单。
问题是客户端组件不支持 aync/await,服务器组件既不支持 useFormState() 也不支持事件处理程序
async function MyForm({id}){
// supported in Client components only
let [state, submitAtion] = useActionState(...);
// await is supported in server components only
let value = await fetch(`https://example.com/value/${id}`);
// event handler is supported in Client components only
clickHandler(ev){
// handle the form
}
return (
<>
<form action={submitAtion}>
<input value={content} onChange={...} />
<button type="submit" />Submit</button>
<button onClick={clickHandler}>Submit</button>
</form>
</>
)
}
试用:
1- 使用服务器操作,但
useActionState()
和 useFormState()
仅在客户端组件中受支持
2- 将
MyForm
转换为客户端组件,但客户端组件不支持 async/await
3-将按钮移动到单独的客户端组件并将表单保留在服务器组件中,但按钮无法访问表单数据,并且我们无法将函数从 MyForm 传递到 MyButton,因为它不是可序列化的值
问题是客户端组件不支持 aync/await
没必要。您可以使用状态来更新从服务器获取的值,并在
useEffect
中获取该值。例如:
function MyForm({id}){
let [state, submitAtion] = useActionState(...);
// track the asynchronous value in state
let [value, setValue] = useState();
// invoke the asynchronous operation whenever "id" changes
useEffect(() => {
(async () => {
// update state with the new value
const response = await fetch(`https://example.com/value/${id}`);
const result = await response.text(); // or json?
setValue(result);
})();
}, [id]);
clickHandler(ev){
// handle the form
}
return (
<>
<form action={submitAtion}>
<input value={content} onChange={...} />
<button type="submit" />Submit</button>
<button onClick={clickHandler}>Submit</button>
</form>
</>
);
}
当组件最初渲染时,
value
将是undefined
(或者如果您愿意的话,将是您为useState()
提供的任何初始值)。 fetch
操作完成后,状态值将被更新,组件将重新渲染。