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>
))
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>
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…