我试图从数据库中提取4个类别。
我得到了类别,一切都很好,但当我提交表格时,我得到了以下数据:
[object%20Object],[object%20Object],[object%20Object],[object%20Object]
这里的代码:
//State
const [cates, setCates] = useState([]);
// Fetch 4 categories
useEffect(() => {
const getCates = async () => {
const res = await axios.get("http://localhost:8080/api/categories");
setCates(res.data);
};
getCates();
}, [])
//Map the categories from the State : cates
const Categorie = cates.map((c) => (
<option value={c.name}>{c.name}</option>
))
我的组件:
<Select>
<option value="" hidden>Choisissez une catégorie</option>
{Categorie}
</Select>
console.log(Categorie)返回一个对象数组:
(4) [{…}, {…}, {…}, {…}]
0
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
1
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
2
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
3
:
{$$typeof: Symbol(react.element), type: 'option', key: null, ref: null, props: {…}, …}
length
:
4
[[Prototype]]
:
Array(0)
console.log(cates[0].name)给了我想要的结果。
但是,即使我尝试手动放置这样的类别:cates[0].name、cates[1].names等……当我保存代码并重新加载页面时,我也会得到一个空白页面。
我只想选择我的类别。
我可以看到Categorie
返回一个react组件数组,而不是从API获取的数据所以你可以这样写
const Component = () => {
const [categories, setCategories] = useState([])
useEffect(() => {
const getCates = async () => {
const res = await axios.get("http://localhost:8080/api/categories");
setCategories(res.data);
};
getCates();
}, [])
const List = () => {
return categories.map(c => (
<option value={c.name}>{c.name}</option>
))
}
return (
<select>
<option value="" hidden>Choisissez une catégorie</option>
<List />
</select>
)
}
列表将是一组react组件,使用它只需添加<List />
Hi@Romain Plantureux
你们可以在上面脱衣服的时候试试这个。
我注意到<Select>
不应该是资本。它一定像那个<select>
。也许这就是为什么你的页面显示为空白。
代码沙盒
我解决了我的问题:
代码+注释:
//UseEffect+状态(没有任何变化,我只是重命名常量):
//for saved the categorie I fecth.
const [cats, setCats] = useState([]);
// for save the value selected in my select :
const [catSelect, setCatSelect] = useState("")
useEffect(() => {
const getCats = async () => {
const res = await axios.get("http://localhost:8080/api/categories");
setCats(res.data);
};
getCats();
}, [])
地图组件,我添加了一个密钥:
const CatSelect = cats.map((c) => (
<option key={c.name} value={c.name} >{c.name}</option>
))
以及Select上最重要的更改:(我使用反作用样式的组件,这就是为什么我的Select有一个大写字母的原因)。
我加了一个值="满"对于OnChange,它将在新状态下保存选定的值。
<Select value={null} onChange={e => setCatSelect(e.target.value)}>
//This first option is important because the default value is not saved automatically in the new state...
<option value="" hidden> Votre choix</option>
{CatSelect}
</Select>