【发布时间】:2020-12-15 19:08:09
【问题描述】:
The initial output of the page load is seen at the top and then a second load returns an array of data. 所以当在 states.map 上调用 map 函数时,我得到了 Uncaught TypeError: states.map is not a function。我不明白为什么。此外,API 调用仅在页面以某种非初始加载的方式重新加载时发生。我可能只是不明白useEffect。为此,该状态的 console.log 什么也没给出。非常感谢任何帮助!
import React, { useState, useEffect } from "react";
import { Component } from "react";
import { Col, Row, Container } from "../components/Grid";
import SiteNav from "../components/SiteNav";
import CoronaCard from "../components/CoronaCard";
import covidAPI from "../utils/covidAPI";
import Footer from "../components/Footer";
import "./style.css"
function CoronaTravelNews() {
// Setting our component's initial state
const [states, setStates] = useState([])
// Load all books and store them with setBooks
useEffect(() => {
loadStates()
}, [])
// Loads all books and sets them to books
function loadStates() {
covidAPI.getCovidInfo()
.then(res =>
setStates(res),
console.log("This is the response: "),
console.log("This is the current state: "),
console.log(states)
)
.catch(err => console.log(err));
};
return (
<div>
<Container>
<Row>
<Col size="md-12">
<SiteNav />
</Col>
</Row>
<Row>
<Col size="md-12">
{states.map(function (state, i) {
return (<CoronaCard
key={i}
province={state.data.key.state}
date={state.data.key.date}
cases={state.data.key.positive}
newCases={state.data.key.positiveIncrease} />)
})}
</Col>
</Row>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<Footer />
<br></br>
</Container >
</div >
);
}
export default CoronaTravelNews;
【问题讨论】:
-
covidAPI.getCovidInfo似乎在您调用它时返回“无” - 因此这反映了返回“无”的控制台日志。我错过了什么?请验证该 API 调用的返回实际上是一个数组。 -
很可能
res是一个对象而不是一个数组。 -
另外,
console.log紧跟在setState之后,记录了 setState 调用未更改的当前渲染状态。更新后的状态仅在下一次渲染时可用,并且由于useEffect运行之后,第一次渲染states将是空的,直到由 setState 触发的下一次渲染。标准做法是有条件地渲染等待获取的第一个渲染。{ states.length && states.map(... -
你能添加console.log(res)的输出吗?
-
setStates(res.data);
标签: javascript reactjs axios