【发布时间】:2020-05-05 11:14:07
【问题描述】:
在下面的代码中,我试图从 API 调用的响应中填充下拉选项标签。不知道为什么它没有显示,因为当我在浏览器中检查调试器时它肯定会到达端点,我得到的只是一个空的下拉菜单。
我的组件代码:
interface ExpensesState {
date: Date;
isLoading: Boolean;
expenses: ICategory[];
categories: ICategory[];
}
const Expenses: React.FC = () => {
const [state, setState] = useState<ExpensesState>({
date: new Date(),
isLoading: true,
expenses: new Array<ICategory>(),
categories: new Array<ICategory>(),
});
const getCategories = () => {
const service = new CategoryService();
service
.getAll()
.then((response) => {
setState({ ...state, categories: response });
setState({ ...state, isLoading: false });
})
.catch((err) => console.log(err));
};
useEffect(() => getCategories(), []);
const handleChange = () => {};
const title = <h3>Add Expense</h3>;
return (
<>
<div>
<AppNav />
<Container>
{title}
<Form>
<FormGroup>
<label htmlFor="title">Title</label>
<input
type="text"
name="title"
id="title"
onChange={handleChange}
/>
</FormGroup>
<FormGroup>
<label htmlFor="Category">Category</label>
<select >
{!state.isLoading
? state.categories.map(({id, name}) => (
<option key={id.toString()} value={name}>{name}</option>
))
: <option>Loading...</option>}
</select>
<input
type="text"
name="category"
id="category"
onChange={handleChange}
/>
</FormGroup>
</Form>
</Container>
</div>
</>
)}
这是我调用 API 的 CategoryService。
class CategoryService {
async getAll(): Promise<ICategory[]> {
const response = await fetch(`/category`, {
method: "GET",
});
return response.ok ? response.json() : null;
}
}
export default CategoryService;
任何帮助将不胜感激。
【问题讨论】:
-
setState内部的双重setState可疑,如果合并它们会发生什么?类似setState({ ...state, categories: response, isLoading: false })
标签: reactjs typescript