【问题标题】:ContextProvider doesn't mount when page refreshes页面刷新时 ContextProvider 不挂载
【发布时间】:2021-01-04 06:29:21
【问题描述】:

请在codesandbox上查看完整代码。

我的国家/地区 api 应用程序有两个 Route 组件-

<>
    <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

无法读取未定义的属性“边框”

发生就行了-

const promises = country[0].borders.map(fetchNeighborName);

country[0] 是从countriesData 中提取的,似乎是undefined-

const {countriesData} = React.useContext(CountriesDataContext);

这不是BrowserRouter 的问题,因为DetailsRoute 组件会渲染但缺少信息。

我不知道当 直接 url 请求 发送到 DetailsRoute 组件时是什么逻辑错误导致它无法工作?请告诉我解决方法!

【问题讨论】:

  • 我认为这可能与stackoverflow.com/questions/53453861/…有关
  • @MehmetAliPeker 我无法将其与我的问题联系起来。我在CountriesDataContext 中设置断点 时看到的问题是,在重新加载时,componentDidMount 不执行,这就是我获取国家/地区数据的地方。

标签: javascript reactjs use-context


【解决方案1】:

问题是,当您重新加载详细信息页面时,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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-13
    • 2012-11-14
    • 2023-03-11
    • 2020-04-03
    • 1970-01-01
    • 2016-11-21
    • 2012-09-21
    • 2012-12-13
    相关资源
    最近更新 更多