gpt4 book ai didi

javascript - 如何在 Context API 中传递路由参数

转载 作者:行者123 更新时间:2023-12-04 16:40:51 24 4
gpt4 key购买 nike

我正在使用上下文 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

Codesandbox Link

项目 Github link

最佳答案

您可以通过传递更新上下文状态的 setter 函数从使用它的组件更新上下文。

export default function CountryContextProvider({ children }) {
const [countries, setCountries] = useState([]);
const [country, setCountry] = useState([]);
const [path, setPath] = useState('');

useEffect(() => {
async function getSingleCountryData() {
const result = await axios(`your/request/for/${path}`);
setCountry(result.data);
}
if(path) getSingleCountryData();
}, [path]);

return (
<CountryContext.Provider value={{ countries, country, setPath }}>
{children}
</CountryContext.Provider>
);
}

现在使用 setPath安装此组件后,使用路由匹配更新请求端点。
const Details = ({ match }) => {
const {
params: { alpha3Code }
} = match;
const { country, setPath } = useContext(CountryContext);

useEffect(() => {
setPath(alpha3Code);
}, [alpha3Code]);

return (
<main>Some JSX here</main>
);
};

export default withRouter(Details);

链接是一个工作 codesandbox implementation

关于javascript - 如何在 Context API 中传递路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61003469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com