【发布时间】:2021-08-18 20:19:49
【问题描述】:
当我在我的应用上重新加载“详细信息”页面(不是主页)时,出现错误:
“TypeError: 'country' 的属性 'flag' 未定义,因此无法解构。”
我猜由于数据是从主页传递到另一个,如果我们不从主页转到详细信息页面,我们就无法从 API 加载数据。
经过一些研究,我得出结论,我必须修改 webpack.config.js 中的一些内容,但是当我使用以下命令创建我的应用程序时:
npx create-react-app my-app
我很难找到 webpack 配置文件,我什至不确定这是否是解决方案。
主页上的卡片(点击后会转到特定国家/地区的详细信息页面):
import { Link } from 'react-router-dom';
const Card = ({country}) => {
const {flag, name, population, subregion, capital} = country;
const new_population = population.toLocaleString();
const newTo = {
pathname: `/details/${name}`,
country: country
};
return <Link to={newTo} className='card'>
<img src={flag} alt={name}></img>
<div className='subCard'>
<h2>{name}</h2>
<p>Population: {new_population}</p>
<p>Region: {subregion}</p>
<p>Capital: {capital}</p>
</div>
</Link>;
}
export default Card;
点击卡片后进入的页面:
import { useLocation, Link } from 'react-router-dom';
const Details = () => {
const { country } = useLocation();
const {
flag,
name,
nativeName,
population,
region,
subregion,
capital,
topLevelDomain,
currencies,
languages,
borders } = country;
//arrays: currencies, languages, borders, topLevelDomain
return <div className='details'>
<Link to={`/`} >Back</Link>
<img src={flag} alt={name}></img>
//etc
</div>;
export default Details;
}
我的主页:
import React, { useState, useEffect } from 'react';
import { useFetch } from './useFetch'
import Card from './Card';
import Searchbar from './Searchbar';
const Home = () => {
const [url, setUrl] = useState('https://restcountries.eu/rest/v2/all');
const { isLoading, countries, isError } = useFetch(url); //custom hook
if(!isLoading && !isError){
return <div className='home'>
<Searchbar setUrl={setUrl}>
<DropdownMenu setRegion={setRegion}></DropdownMenu>
</Searchbar>
<div className='cards'>
{countries.map((country, index)=>{
return <Card key={index} id={index} country={country} ></Card>
})}
</div>
</div>;
//etc
我的App.js(不知道有没有必要):
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Navbar from './Navbar';
//page(s)
import Home from './Home'
import Error from './Error'
import Details from './Details'
function App() {
return (
<Router>
<Navbar></Navbar>
<Switch>
<Route exact path='/'>
<Home />
</Route>
<Route path='/details/:id' children={<Details/>}></Route>
<Route path='*'>
<Error></Error>
</Route>
</Switch>
</Router>
);
}
export default App;
您能否告诉我修改 webpack 配置文件是否是最好的解决方案?如果不是我该怎么办?
顺便说一句,如果您需要我没有在这里显示的代码,我很抱歉,告诉我我会修改我的帖子。
【问题讨论】:
-
我不确定你提出的 webpack 解决方案,但我会做的是
return null,而你的组件道具仍在加载。因此,例如,在您的Card组件中,在您解构country之前编写,检查country是否为假,如果是则返回null。基本上:if (!country) return null
标签: javascript reactjs react-native webpack