请查看 codesandbox 上的完整代码.
我的国家/地区 API 应用程序有两个路线组件-
<>
<Header/>
<Router>
<Switch>
<CountriesDataProvider>
<Route path='/' exact component={HomeRoute} />
<Route path='/detail/:countryName' component={DetailsRoute} />
</CountriesDataProvider>
</Switch>
</Router>
</>
当我在 HomeRoute
上单击一个国家/地区时,每个国家/地区的 DetailsRoute
会完美显示所有信息。但是,当发出直接 http 请求或刷新 DetailsRoute
时,我会看到此错误-
/src/comps/Details/DetailsRoute.jsx
Cannot read property 'borders' of undefined
它发生在线上-
const promises = country[0].borders.map(fetchNeighborName);
country[0]
是从 countriesData
中提取的,它似乎是 undefined
-
const {countriesData} = React.useContext(CountriesDataContext);
这不是 BrowserRouter
的问题,因为 DetailsRoute
组件确实呈现但缺少信息。
当 直接 url 请求 被发送到 DetailsRoute
组件时,我不知道是什么逻辑错误导致它无法工作?请让我知道修复方法!
最佳答案
问题是,当您重新加载详细信息页面时,CountriesDataContext
中的响应尚未返回,因此 country
为空。解决问题的一种简单方法(通常是一种好的做法)是添加检查以确保数据存在:
async function resolveBorders() {
// Add a condition to make sure you have the data you expect.
if (country.length) {
const promises = country[0].borders.map(fetchNeighborName);
setBorderCountries(await Promise.all(promises));
}
}
一定要将 country
添加到效果的依赖数组中,以便效果在响应返回时再次运行:
React.useEffect(() => {
async function resolveBorders() {
...
}
resolveBorders();
}, [borderCountries, country]); // <-- Add `country` here
关于javascript - 页面刷新时 ContextProvider 不挂载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63936736/