设置状态为空对象
const [categories, setCategories] = useState({});
进行axios调用并设置状态。我检查了,res返回正确的数据。
const res = await axios.get(`${API}/categories`);
setCategories(res.data);
};
useEffect(() => {
getCategories()
},[])
创建表单并尝试填充选择栏
<h1>Add New Item</h1>
<section className="form">
<form>
<label htmlFor="category">Category: </label>
<select id="category" required>
<option disabled selected value>
Select A Category
</option>
{Object.keys(categories).map((category) => (
<option value={category.category_id}>{category.name}</option>
))} {console.log(categories)}
</select>
</form>
</section>
代码解决方案: https://stackblitz.com/edit/react-6twagp?file=src/App.js
我试着解决这个
import React from 'react';
import './style.css';
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function App() {
const [categories, setCategories] = useState();
const API = 'https://fakestoreapi.com/';
const getCategories = async () => {
const res = await axios.get(`${API}/products`);
setCategories(res.data);
};
useEffect(() => {
getCategories();
}, []);
return (
<div>
<h1>Add New Item</h1>
<section className="form">
<form>
<label htmlFor="category">Category: </label>
<select id="category" required>
<option disabled selected value>
Select A Category
</option>
{categories &&
categories.map((category) => (
<option value={category.id}>{category.title}</option>
))}
</select>
</form>
</section>
</div>
);
}