gpt4 book ai didi

javascript - 无法读取未定义的属性 'map' - 无法从 axios 请求映射数据

转载 作者:行者123 更新时间:2023-11-30 23:58:55 24 4
gpt4 key购买 nike

在 React 中,我尝试从我创建的 API 调用中获取数据。控制台打印出正确的响应,即用户名列表,但映射对我不起作用。任何建议都会有益。

import React, { useEffect } from "react";
import { useForm } from "react-hook-form";
import axios from "axios";

const CreateProject = () => {
const [loading, setLoading] = React.useState(true);
const { handleSubmit, register, errors } = useForm();
const [value, setValue] = React.useState("Choose option");
const [items, setItems] = React.useState([
{ label: "Loading", value: "Loading" }
]);
const onSubmit = values => {
console.log(values);
};
useEffect(() => {
// initialise as false
let unmounted = false;
async function getUsers() {
const res = await axios.get(
"http://localhost:3000/api/findUser/findUser"
// Api for finding user
);
const body = await res.data;
console.log(res.data);
// check state is still false beofre state is set
if (!unmounted) {
setItems(
body.res.map(({ name }) => ({
label: name,
value: name
}))
);
setLoading(false);
// setLoading allows change to option - data displayed
}
}
getUsers();
return () => {
unmounted = true;
};
}, []);

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
type="text"
placeholder="ProjectName"
name="ProjectName"
ref={register({ required: true, maxLength: 20 })}
/>
<input
type="text"
placeholder="Project Details"
name="Project Detail"
ref={register({ required: true, maxLength: 50 })}
/>
<select
disabled={loading}
value={value}
onChange={e => setValue(e.currentTarget.value)}
>
{items.map(({ label }) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
{errors.search && <p>No user found</p>}
<input type="submit" />
</form>
);
};

export default CreateProject;

我收到的错误似乎是在 setItems 处的 body.res.map 周围 - “未捕获( promise 中)TypeError:无法读取未定义的属性“map””

最佳答案

您实际上是在控制台记录除您映射的变量之外的其他变量。如果您记录的内容是正确的,您的 setItems() 应该是:

setItems(
res.data.map(({ name }) => ({
label: name,
value: name
}))
)

关于javascript - 无法读取未定义的属性 'map' - 无法从 axios 请求映射数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60875230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com