【问题标题】:Fetching data from API and react-router-dom on refresh / direct link在刷新/直接链接时从 API 和 react-router-dom 获取数据
【发布时间】:2021-02-20 12:08:24
【问题描述】:

我正在使用 react-router-dom 和 react-connected-router 为一个应用学习 redux 和路由和历史。我有一个 api,我在 componentDidMount() 中执行 fetchData:

  componentDidMount() {
    const { onFetchData, prodPerPage, currentPage, filters } = this.props;
    onFetchBooks(prodPerPage, currentPage, filters);
  }

在我的分页组件中,我使用了一个链接,该链接路由到在单击时可以正常工作的页面,因为我在单击时重新获取数据,其中 currentPage 成为 pageIndex,因此为该页面获取数据。

这是我的链接:

 <Link to={`/products/page/${item.page}`}>
   <PaginationItem {...item} />
 </Link>

这是我的路线:

<Route exact path="/products/page/:page" component={ProductsPage} />

如果我重新加载我的页面,我的 currentPage 会从 initialState 设置为 1。 在后退/前进时,我的页面再次加载第 1 页的数据。

如何将我的 currentPage 设置为我导航到的任何内容?因此,如果我的链接是 https://localhost:3000/products/page/3 则将 currentPage 设置为 3 并获取正确的数据?

注意:如果我尝试加载 https://localhost:3000/products/page/3sddada 它不会重定向到 404,我该如何解决这个问题?

提前致谢。

【问题讨论】:

    标签: reactjs react-redux react-router-dom


    【解决方案1】:

    我们需要访问传递到路由中的动态 pageid,并使用它从 API 查询正确的页面。使用 react-router-dom 很容易做到这一点。该库将一个名为 match 的道具传递到每个渲染的路由中。在这个匹配对象内部是另一个名为 params 的对象。这包含所有匹配的参数,其中键是我们在创建路由时指定的名称,值是 URL 中的实际值。

     componentDidMount() {    
          const { page} = this.props.match.params;
          this.setState({currentPage:page});
          const { onFetchData, prodPerPage, filters } = this.props;
          onFetchBooks(prodPerPage, currentPage, filters);
          
        }
    

    React-router v4 现在允许您使用正则表达式来匹配参数 -- https://reacttraining.com/react-router/web/api/Route/path-string

    <Switch>
        <Route exact path="/products/page/:page(\\d+)" component={ProductsPage}/>
        <Route exact path="/products/page/:page(\\w+)" component={ErrorRedirectPage}/>
    </Switch>
    

    【讨论】:

    • 太棒了,谢谢!唯一的问题是开关不起作用。必须使用 path="/products/page/:page(\d+)" 然后错误重定向 path="*" 并且它现在可以工作了。
    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 2019-11-28
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多