我需要创建一个React应用,让您列出宠物小精灵和类型。 我从PokeAPI获取数据。从App组件中获取它,然后将其传递给子组件是一种好习惯,还是从子组件中获取它们更好?
我正在主应用程序中获取它,我可以看到获取结果,因为我在console.log中记录了数据,但是我的组件没有获取它,因此我得到了props.map不是其中的函数
这是我的App.js:
import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";
import axios from "axios";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import PokemonList from "./components/PokemonList";
const App = (props) => {
const [pokemons, setPokemons] = useState([]);
const [types, setTypes] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const getPokemons = () => {
const axios = require("axios").default;
axios.get("https://pokeapi.co/api/v2/pokemon").then(function (response) {
console.log("Fetched pokemons");
console.log(response.data.results);
setIsLoading(false);
setPokemons(response.data.results);
});
};
const getTypes = () => {
setIsLoading(true);
const axios = require("axios").default;
axios.get("https://pokeapi.co/api/v2/type").then(function (response) {
console.log("Fetched types");
console.log(response.data.results);
setIsLoading(false);
setTypes(response.data.results);
});
};
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/pokemons" onClick={getPokemons}>
Pokemons
</Link>
</li>
<li>
<Link to="/types">Types</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/pokemons">
<Pokemons pokemons={pokemons} />
</Route>
<Route path="/types">
<Types />
</Route>
</Switch>
</div>
</Router>
);
};
function Pokemons(pokemons) {
return <PokemonList props={pokemons} />;
}
function Types(typeList) {
return <h2>TYPES:</h2>;
}
export default App;
这是我的PokemonList.js:
import React from "react";
import { Card } from "semantic-ui-react";
import PokeCard from "./PokeCard";
const Pokemonlist = (props) => {
let content = (
<Card.Group>
{props.map(function (object, i) {
return <PokeCard pokemon={object} key={i} />;
})}
</Card.Group>
);
return content;
};
export default Pokemonlist;
最后是我的PokeCard.js
import { Card, Image } from "semantic-ui-react";
import React from "react";
const PokeCard = (pokemon) => {
let content = (
<Card>
<Card.Content>
<Image floated="right" size="mini" src={pokemon.img} />
<Card.Header>{pokemon.name}</Card.Header>
<Card.Meta>{pokemon.base_experience}</Card.Meta>
<Card.Description>ID: {pokemon.id}</Card.Description>
</Card.Content>
</Card>
);
return content;
};
export default PokeCard;
所以基本思想是:
在主页上单击Pokemons按钮,该按钮将调用fetch,然后呈现PokemonList组件,该组件基本上只是从我获取的数据中呈现多个PokeCard组件。
1,我在这里想念什么?
2,在我什么都没有改变的情况下,我需要使用useEffect吗?
3,我什么时候应该提取数据,在哪里?
编辑:我想使用零类的钩子
答案 0 :(得分:1)
这是我的答案的摘要
App
钩子获取结果undefined
组件的useEffect挂钩中,因为子组件在将道具传递给它之前就已经渲染了,这就是您收到df %>%
group_by(Site) %>%
arrange(desc(Date)) %>%
slice(1:3) %>%
mutate(
id_within = str_c("M_", 1:3),
Date = format(Date, "%b %Y")
) %>%
pivot_wider(
id_cols = Site,
names_from = id_within,
values_from = Date
)
错误的原因