javascript - 使用 select 在表单中选择类别
问题描述
我有反应应用程序。在这个应用程序中,我有带有 post( title
, category_id
, description
, image
)的页面
但是现在在带有帖子的页面上,我需要创建在我的本地服务器form
中添加新帖子。这个表格有,的 输入title
,我应该在. 我使用和 API 方法从本地服务器获取的类别列表description
image
category
select
fetch
GET
我做了一些事情,但在某些地方我不知道该写什么。
在某些地方写什么而不是/*.....*/
在文件 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>
);};
解决方案
根据您的代码,您正在从服务器获取所有类别。我会将您的代码更改为以下内容:
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,它有一个值。
推荐阅读
- r - 下载 MODIS NDVI 数据时 MODIStsp 出错
- prometheus - 由于缺少数据,使用多个副本在单个指标上查询普罗米修斯
- python - 在 azure synapse 中实现 azcopy 的 Python 程序
- python - 使用参考卷将 .nrrd 分段转换为 Nifti 卷
- elasticsearch - 如何创建动态弹性搜索查询......输入参数可能会改变
- php - 需要帮助将此 VB.NET 函数转换为 PHP
- java - 尝试注册后android应用程序出错
- azure - Azure 数据工厂:仅在新文件上触发存储事件
- python - 如何获得一维数组和二维数组的平均值?
- c++ - 运行时错误:将非零偏移量 18446744073709551615 应用于空指针 (basic_string.h)