【发布时间】:2021-11-23 18:21:55
【问题描述】:
我是 React 新手,我无法找到任何解决我的问题的方法。我正在成功加载第一个获取请求,然后我使用 lodash 从数组中获取一个随机元素,并使用该信息创建一个新 URL,但我无法使用与第一个 API 调用完全相同的方法创建一个数组.请有人可以帮助我如何创建新的 axios.get 请求?
import axios from "axios";
import React from "react";
import _ from 'lodash';
export default function App() {
const baseURL = "http://apiv3.iucnredlist.org/api/v3/region/list?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee";
const [list, setList] = React.useState(0);
const [error, setError] = React.useState(0);
//get List of available regions
React.useEffect(() => {
axios.get(baseURL).then((response) => {
setList(response.data);
}).catch(error => {
setError(error);
})
}, []);
if (error) return `Error: ${error.message}`;
if (!list) return null;
//Take a random region from the list
const randomRegion = _.sample(list.results);
console.log(randomRegion)
//Load the list of all species in the selected region
const selectedRegion = "http://apiv3.iucnredlist.org/api/v3/species/region/"+ randomRegion.identifier + "/page/0?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee"
console.log(selectedRegion)
const [speciesList, selectedRegionList] = React.useState(0);
React.useEffect(() => {
axios.get(selectedRegion).then((response) => {
selectedRegionList(response.data);
}).catch(error => {
setError(error);
})
}, []);
return (
<div>
</div>
);
}
【问题讨论】:
-
不清楚你的问题是什么。您的第二个 axios 请求是否出现错误?
-
在第二个 React.useEffect 之后我有这个错误:有条件地调用 React Hook "React.useState"。在每个组件渲染中,必须以完全相同的顺序调用 React Hooks。
标签: javascript reactjs axios react-hooks