React JS-Uncaught TypeError:states.map不是函数//useEffect问题



页面加载的初始输出显示在顶部,然后第二次加载返回一个数据数组。因此,当调用states.map上的map函数时,我得到了Uncaught TypeError:states.map不是一个函数。我不明白为什么。此外,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;

在您的返回语句中,您应该添加这个

return (
<div>
{states.length==0 
? (<p>Loading ... </p>)    //add a loader or return null when states = []
: (<Container> ...your jsx... </Container>)    // else, return your jsx
}
</div>
);

相关内容

  • 没有找到相关文章

最新更新