最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How Do I Preserve Selected Value in a React <select> Field After Form Submission Using useActionState

programmeradmin4浏览0评论

I am working with a React form component, and I have a select field inside it. When the form is submitted, I want to preserve the selected value (the default value) in the select field. However, after the form is submitted, the default value resets to the first option, which is not what I want.

This issue seems to be happening only with the <select> field, as similar behavior works with text inputs (they retain their values correctly).

How can I prevent the select field from resetting its value after the form is submitted whilst using useActionState?

import { useActionState } from "react";

function Form() {
  const [formData, formAction, isPending] = useActionState(async (previous, current) => current, new FormData);

  // After submission does log selected value
  console.log(formData.get('example'))
  
  return (
    <form action={formAction}>
      <select name="example" defaultValue={formData.get('example')}>
        <option value='1'>1</option>
        <option value='2'>2</option>                       
      </select>
      <button type='submit'>Submit</button>
    </form>
  );
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论