【发布时间】:2020-07-15 03:01:40
【问题描述】:
我正在使用上下文 API,我的上下文文件中有这个:
useEffect(() => {
async function getSingleCountryData() {
const result = await axios(
`https://restcountries.eu/rest/v2/alpha/${props.match.alpha3Code.toLowerCase()}`
);
console.log(result)
setCountry(result.data);
}
if (props.match) getSingleCountryData();
}, [props.match]);
在我正在使用的组件中,它不起作用,因为它不知道 props.match.alpha3Code 是什么。我怎样才能传递价值? alpha3Code 来自 URL:localhost:3000/country/asa 其中asa 是 alpha3Code,我怎样才能得到这个值?
基本上,我想做的是。我有一个我在主页上列出的国家列表。现在,我正在尝试获取有关单个国家/地区的更多信息。路由是/country/:alpha3Code,其中alpha3Code 是从API 获取的。
FWIW,这是我的完整上下文文件:
import React, { useState, createContext, useEffect } from 'react';
import axios from 'axios';
export const CountryContext = createContext();
export default function CountryContextProvider(props) {
const [countries, setCountries] = useState([]);
const [country, setCountry] = useState([]);
useEffect(() => {
const getCountryData = async () => {
const result = await axios.get(
'https://cors-anywhere.herokuapp.com/https://restcountries.eu/rest/v2/all'
);
setCountries(result.data);
};
getCountryData();
}, []);
useEffect(() => {
async function getSingleCountryData() {
const result = await axios(
`https://restcountries.eu/rest/v2/alpha/${props.match.alpha3Code.toLowerCase()}`
);
console.log(result)
setCountry(result.data);
}
if (props.match) getSingleCountryData();
}, [props.match]);
return (
<CountryContext.Provider value={{ countries, country }}>
{props.children}
</CountryContext.Provider>
);
}
在我使用country 的组件中,我有:
const { country } = useContext(CountryContext);
我知道我可以从组件本身执行此操作,但我正在学习如何使用上下文 API,因此我正在处理我的上下文中的所有 API 调用。
我正在使用的 API 是 here
项目 Github link
【问题讨论】:
标签: javascript reactjs react-router react-hooks