Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

javascript - how to use individual component from an API by calling dynamically in React?

I implement a project where i have to call API. From this API enter link description here first i show 250 countries and then create a details component where show all details individually by clicking a button or link. But i faced some problem. Since i have a little knowledge about react and API so i didn't understand how to call API for individually show country details in my details component. I need help because i want to know that how can I dynamically call single country from 250 countries API

enter image description here ----------This is the component here i load all countries by calling rest API. After that i couldn't call any single country

enter image description here This is my country details component where i want to load individual country details

enter image description here After getting some help i understand that api is coming in useState but i can not implement

import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
const CountryDetails = () => {
const {countryName} = useParams();
const [country,setCountry] = useState([]);  //use object
console.log(countryName);
console.log(country[0]);
useEffect(()=>{
    // const url = `https://restcountries.eu/rest/v2/all`;
    const url = `https://restcountries.eu/rest/v2/name/${countryName}`;
    fetch(url)
    .then(res => res.json())
    .then(data => setCountry(data));
},[countryName])
// console.log(country);
return (
    <div>
        <h3>This is  {countryName}</h3>
        {/* <h2>{country[0]}</h2> */}
        <h4>{countryName.capital}</h4>
    </div>
); }; export default CountryDetails;

this is App.js in my project

import './App.css';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useParams,
useRouteMatch 
} from "react-router-dom";
import Home from './Components/Home/Home';
import CountryDetails from './Components/CountryDetails/CountryDetails';
import NotFound from './Components/NotFound/NotFound';
function App() {
return (
<Router>
  <Switch>
    <Route path="/home">
      <Home/>

    </Route>
    <Route path="/:countryName">
      <CountryDetails></CountryDetails>
    </Route>
    <Route exact path="/">
      <Home />
    </Route>
    <Route path="*">
      <NotFound></NotFound>
    </Route>
  </Switch>
 </Router>
 );
 }  export default App;

I need to implement this component for showing individual country details


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the issue is with how you attempt to render the details. The country data will still be in array format. countryName is the string route parameter, so it won't have any country specific properties to call.

<div>
    <h3>This is  {countryName}</h3>
    {/* <h2>{country[0]}</h2> */}
    <h4>{countryName.capital}</h4> // <-- countryName is string!!
</div>

You can simply map the country results similarly to how it was done on the main page. Destructure the detail values you want to use for rendering the details.

return country.map(({ capital, name }) => ( // <-- destructure all values needed
  <div key={name} className="country">
    <h3>
      Country Name: {name}
    </h3>
    <div>
      Capital: {capital}
    </div>
    <button type="button" onClick={history.goBack}>Back</button>
  </div>
))

enter image description here

Edit how-to-use-individual-component-from-an-api-by-calling-dynamically-in-react

Full Demo Code:

Home page

const Home = () => {
  const [countries, setCountries] = React.useState([]);

  React.useEffect(() => {
    fetch("https://restcountries.eu/rest/v2/all")
      .then((res) => res.json())
      .then((data) => setCountries(data));
  }, []);

  const history = useHistory();

  return countries.map(({ capital, name }) => (
    <div key={name} className="country">
      <div>Country Name: {name}</div>
      <div>Capital: {capital}</div>
      <button
        type="button"
        onClick={() =>
          history.push({
            pathname: `/${name}`
          })
        }
      >
        Details
      </button>
    </div>
  ));
};

Details page

const CountryDetails = () => {
  const { countryName } = useParams();

  const [country, setCountry] = React.useState([]);

  React.useEffect(() => {
    fetch(`https://restcountries.eu/rest/v2/name/${countryName}`)
      .then((res) => res.json())
      .then((data) => setCountry(data));
  }, [countryName]);

  const history = useHistory();

  return country.map(
    ({ capital, flag, name, nativeName, population, region, subregion }) => (
      <div key={name} className="country">
        <h3>Country Name: {name}</h3>
        <img
          src={flag}
          alt="flag"
          style={{
            height: "100px"
          }}
        />
        <div>Capital: {capital}</div>
        <div>Region: {region}</div>
        <div>Subregion: {subregion}</div>
        <div>Population: {population}</div>
        <div>Native Name: {nativeName}</div>
        <button type="button" onClick={history.goBack}>
          Back
        </button>
      </div>
    )
  );
};

App

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <Router>
        <Switch>
          <Route path="/:countryName">
            <CountryDetails />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </Router>
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...