首页 > 解决方案 > 使用 select 在表单中选择类别

问题描述

我有反应应用程序。在这个应用程序中,我有带有 post( title, category_id, description, image)的页面

但是现在在带有帖子的页面上,我需要创建在我的本地服务器form中添加新帖子。这个表格有,的 输入title,我应该在. 我使用和 API 方法从本地服务器获取的类别列表descriptionimagecategoryselectfetchGET

我做了一些事情,但在某些地方我不知道该写什么。

在某些地方写什么而不是/*.....*/在文件 SelectCategory.js 中?

来自服务器的响应(我进入的类别列表const data):

{"data":
[{"id":20,"title":"auto"},
{"id":21,"title":"sport"},
{"id":23,"title":"new"}
]}

选择类别.js:

const SelectCategory = () => {
    
  const [value, setValue] = useState({
    listCategory: [],
    selectCategory: ''
});
      
    useEffect(() => {
       fetchData(); 
     }, [/*.....*/]);
    
    async function fetchData() {
      try {
        const data = await api(`${listRoute}`, {
          method: 'GET',
         });
          setValue(prev => ({
            ...prev,
            listCategory: data.data,
         }));
    
      } catch (e) {
        console.error(e);
      }
    }

    const upadateSelectCategory = (/*.....*/) => {         
     setValue({
        ...value,
        selectCategory: /*.....*/,
    });
   };
    
    return (
      <div>
        <select onChange={upadateSelectCategory} value={value.selectCategory}>
          <option value="">-- Category --</option>
          {/*.....*/.map(item => <option key={/*.....*/}>{/*.....*/}</option>)}  
        </select> 
      </div>
  );
}


AddPost.js:

const AddImage = () => {
      
 // THERE SOME CODE
    
   return (
    <div>
        <form onSubmit={handleSubmit} ref={formRef}>
          <input type="text" name="title"/>
          <SelectCategory />
          <input type="text" name="description"/>
          <input type="file" name="image" accept="image/*"/>

          <button type="submit">Add</button>
       </form>
   </div>
  );};

标签: javascriptreactjs

解决方案


根据您的代码,您正在从服务器获取所有类别。我会将您的代码更改为以下内容:

const SelectCategory = () => {
  const [category, setCategory] = useState('')
  const [categories, setCategories] = useState([])

    useEffect(() => {
       fetchData(); 
     }, []);

    async function fetchData() {
      try {
        const data = await api(`${listRoute}`, {
          method: 'GET',
         });
          setCategories(data.data.map(cat => cat.title)
      } catch (e) {
        console.error(e);
      }
    }

    const upadateSelectCategory = e => {         
     setCategory(e.target.value);
   };

    return (
      <div>
        <select onChange={upadateSelectCategory} value={category}>
          <option value="">-- Category --</option>
          {categories.map(item => <option key={item}>{item}</option>)}  
        </select> 
      </div>
  );
}

useEffect 只会执行一次。我们映射数据以获取类别的所有标题。select 上的 onChange 发送一个事件,该事件有一个目标 - select,它有一个值。


推荐阅读