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

标签 javascript reactjs react-router react-hooks

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

相关文章:

reactjs - 在react-router中,this.context.router的类型是什么?

javascript - React 路由器不工作需要模块

javascript - 当复选框的容器还包含任何图像时,复选框会触发事件两次

javascript - 如果 API 响应太快,React componentWillReceiveProps 检查不起作用

javascript - 使用 React 和 Redux 进行 api 调用队列?

reactjs - 如何在不使用路由器的情况下向 React 添加页面转换?

javascript - 我们应该将 Jquery 与 React 一起使用吗?有什么好处和坏处

javascript - 通过 promise 从多个来源获取数据

javascript - JQuery 移动动态 ListView API

javascript - 为什么子组件的 prop 只显示父组件的初始值?