React Router Link 更改 URL 但不呈现组件 - Rest Countries API

React Router Link changes URL but doesn't render Component - Rest Countries API

提问人:Ope Afolabi 提问时间:6/15/2021 最后编辑:Drew ReeseOpe Afolabi 更新时间:6/16/2021 访问量:461

问:

我正在按照 frontendmentor (https://www.frontendmentor.io/challenges/rest-countries-api-with-color-theme-switcher-5cacc469fec04111f7b848ca) 的 Rest Countries API 挑战构建一个应用程序。我遇到了一个问题。单击 countryDetail.js 中的路由器链接时,url 会更改,但除非刷新页面,否则不会重新呈现组件。

国家/地区详细信息.js

import React, { useState, useEffect } from "react";
import axios from "axios";
import {Link} from "react-router-dom";
import {CountryDetailStyles, ImgContainer, CountryInfo, CountryInfoDetails, CountryDetailsWrapper, CountryInfoDetailsInner, CountryBorders, LinkWrapper} from "../styles/CountryDetailStyles";

function CountryDetail({match, history}) {

  const [item, setItem] = useState([]);
  const [allCountries, setAllCountries] = useState([]);

  useEffect(() => {
     fetchItem();
     setBorderCountries();
  }, []);

  const fetchItem = async () => {
    const response = await axios.get(`https://restcountries.eu/rest/v2/name/${match.params.name}?fullText=true`);
    setItem(response.data)
  }

  const setBorderCountries = async () => {
    const response = await axios.get(`https://restcountries.eu/rest/v2/all`);
    setAllCountries(response.data)
  }

  // get borders full name using alpha3code
  const getBorderCountryName = (allCountries, border) => {
    const matchingCountry = allCountries.find(country => {
      return country.alpha3Code === border;
    })

     return matchingCountry.name;
  }
    
  return (
       <CountryDetailStyles>
           <Link className="country-links" to={"/"}>
             <LinkWrapper>
             <p><i className="fas fa-arrow-left"></i>Go Back</p>
             </LinkWrapper>
             </Link>
           {
            item.length > 0 && item.map(i => (   
               <CountryDetailsWrapper>           
               <ImgContainer flag={i.flag}>
               </ImgContainer>
               <CountryInfo>
                   <h1>{i.name}</h1>
                   <CountryInfoDetails>
                       <CountryInfoDetailsInner>
                       <p><span>Native Name: </span>{i.nativeName}</p>
                       <p><span>Population: </span>{i.population.toLocaleString()}</p>
                       <p><span>Region: </span>{i.region.length > 0 ? i.region : 'N/A'}</p>
                       <p><span>Sub Region: </span>{i.subregion.length > 0 ? i.subregion : 'N/A'}</p>
                       <p><span>Capital: </span>{i.capital.length > 0 ? i.capital : 'N/A'}</p>
                       </CountryInfoDetailsInner>
                       <CountryInfoDetailsInner className="second">
                       <p><span>Top Level Domain: </span>{i.topLevelDomain}</p>
                       <p><span>Currencies: </span>{i.currencies[0].name}</p>
                       <p><span>Languages: </span>{i.languages.map(lang => lang.name).join(", ")}</p>
                       </CountryInfoDetailsInner>
                   </CountryInfoDetails>
                   <CountryBorders>
                       <p><span>Border Countries:</span></p>
                    {allCountries.length > 0 && i.borders.map(border => {
                      const borderName = getBorderCountryName(allCountries, border);
                      return (<Link to={`/country/${borderName.toLowerCase()}`}><button>{borderName}</button></Link>)
                    })}
                   </CountryBorders>
               </CountryInfo>
               </CountryDetailsWrapper>
           ))
           }
        </CountryDetailStyles>
  )
}

export default CountryDetail;

App.js

import './App.css';
import { ThemeProvider } from 'styled-components';
import { lightTheme, darkTheme } from './styles/themes';
import { GlobalStyles } from './styles/global';
import { useState } from 'react';
import Navbar from './components/Navbar';
import { useDarkMode } from './hooks/useDarkMode';
import CountryList from './components/CountryList';
import CountryDetail from './components/CountryDetail';
import {Route} from "react-router-dom";


function App() {
  const [theme, toggleTheme] = useDarkMode();
  const themeMode = theme === 'dark' ? darkTheme : lightTheme;

  return (
    <div className="App">
      <ThemeProvider theme={themeMode}>
        <GlobalStyles />
        <Navbar navTheme={theme} toggleTheme={toggleTheme} />
        <Route exact path="/" component={CountryList} />
        <Route exact path="/country/:name" component={CountryDetail} />
      </ThemeProvider>
    </div>
   
  );
}

export default App;

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
  <BrowserRouter>
    <App />
    </BrowserRouter>,
  document.getElementById('root')
);

 
reportWebVitals();
javascript reactjs api 反应钩子 react-router-dom

评论

0赞 Calvin 6/15/2021
你能试着把你的路线包装在<Switch>中吗?
0赞 Ope Afolabi 6/15/2021
不幸的是:(没有工作
0赞 Nikki9696 6/15/2021
第二条路线应该有一个“精确”的吗?
0赞 Ope Afolabi 6/16/2021
删除了确切的,仍然不起作用:(

答:

2赞 Drew Reese 6/16/2021 #1

问题

问题似乎是您已经在路上并且正在点击访问另一个国家。路由器正确更新了地址栏中的 URL,但由于已挂载,因此忽略了重新计算 and 状态。这是因为钩子在组件挂载时只运行一次。"/country/:name"CountryDetailitemallCountriesuseEffect

溶液

param()实际上是GET请求的依赖项,它应该被添加到钩子的依赖项数组中。namematch.params.nameuseEffect

useEffect(() => {
 fetchItem();
 setBorderCountries();
}, [match.params.name]);

const fetchItem = async () => {
  const response = await axios.get(
    `https://restcountries.eu/rest/v2/name/${match.params.name}?fullText=true`
  );
  setItem(response.data);
}

建议

它似乎没有这种依赖关系,所以我建议将其拆分为带有空依赖项数组的钩子,这样您就可以在组件挂载时只获取一次此数据。allCountriesuseEffect

useEffect(() => {
 setBorderCountries();
}, []);

useEffect(() => {
 fetchItem();
}, [match.params.name]);