JavaScript UseState.map 不是函数
JavaScript UseState.map is not a function
我正在使用 reactjs 尝试获取并列出我页面中的事件。根据 console.log(incidents),incidents 是一个空数组,但是当我 运行 它时 return 是:
TypeError: incidents.map is not a function
export default function Profile() {
const ongName = localStorage.getItem("ongName");
const ongID = localStorage.getItem("ongID");
const history = useHistory();
const [incidents, setIncidents] = useState([]);
useEffect(() => {
async function a() {
api.get('profile', {
headers: {
Authorization: ongID,
},
}).then((response) => {
console.log(response.data)
setIncidents(response.data);
});
}
a();
}, [ongID]);
return (
<div className="profile-container">
<ul>
{console.log(incidents),
incidents.map(incident => (
<li key={incident.id}>
<strong>Caso:</strong>
<p>{incident.titulo}</p>
</li>
))}
</ul>
</div>
);
}
index.js:67 []length: 0__proto__: Array(0)
index.js:67 []length: 0__proto__: Array(0)
index.js:22 {incidents: Array(2)}incidents: Array(2)0: {id: 7, titulo: "csa", desc: "dsadsa", valor: "dsa", ong_id: "857bc663"}1: {id: 8, titulo: "asf", desc: "sdf", valor: "d", ong_id: "857bc663"}length: 2__proto__: Array(0)__proto__: Object
index.js:67 {incidents: Array(2)}
index.js:67 {incidents: Array(2)}
您的日志似乎表明 response.data 是一个事件数组为 属性 的对象。
你可以尝试替换 :
setIncidents(response.data);
与:
setIncidents(response.data.incidents);
我正在使用 reactjs 尝试获取并列出我页面中的事件。根据 console.log(incidents),incidents 是一个空数组,但是当我 运行 它时 return 是:
TypeError: incidents.map is not a function
export default function Profile() {
const ongName = localStorage.getItem("ongName");
const ongID = localStorage.getItem("ongID");
const history = useHistory();
const [incidents, setIncidents] = useState([]);
useEffect(() => {
async function a() {
api.get('profile', {
headers: {
Authorization: ongID,
},
}).then((response) => {
console.log(response.data)
setIncidents(response.data);
});
}
a();
}, [ongID]);
return (
<div className="profile-container">
<ul>
{console.log(incidents),
incidents.map(incident => (
<li key={incident.id}>
<strong>Caso:</strong>
<p>{incident.titulo}</p>
</li>
))}
</ul>
</div>
);
}
index.js:67 []length: 0__proto__: Array(0)
index.js:67 []length: 0__proto__: Array(0)
index.js:22 {incidents: Array(2)}incidents: Array(2)0: {id: 7, titulo: "csa", desc: "dsadsa", valor: "dsa", ong_id: "857bc663"}1: {id: 8, titulo: "asf", desc: "sdf", valor: "d", ong_id: "857bc663"}length: 2__proto__: Array(0)__proto__: Object
index.js:67 {incidents: Array(2)}
index.js:67 {incidents: Array(2)}
您的日志似乎表明 response.data 是一个事件数组为 属性 的对象。
你可以尝试替换 :
setIncidents(response.data);
与:
setIncidents(response.data.incidents);