Reactjs 从API获取数据并在刷新/直接链接上响应路由器dom

Reactjs 从API获取数据并在刷新/直接链接上响应路由器dom,reactjs,react-redux,react-router-dom,Reactjs,React Redux,React Router Dom,我正在学习react router dom和react connected router应用程序的redux、路由和历史。我有一个api,在componentDidMount()中获取数据: 在我的分页组件中,我使用了一个链接,该链接路由到一次单击就可以正常工作的页面,因为我在单击currentPage成为pageIndex的地方重新获取数据,以便为该页面获取数据 这是我的链接: <Link to={`/products/page/${item.page}`}> <Pa

我正在学习react router dom和react connected router应用程序的redux、路由和历史。我有一个api,在componentDidMount()中获取数据:

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

这是我的链接:

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

这是我的路线:

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

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

如何将当前页面设置为导航到的任何页面?所以如果我的链接是https://localhost:3000/products/page/3 然后将currentPage设置为3并获取正确的数据

注意:如果我尝试加载https://localhost:3000/products/page/3sddada 它不会重定向到404,我如何修复它呢


提前感谢。

我们需要访问传递到路由中的动态pageid,并使用它从API查询正确的页面。使用react路由器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现在允许您使用正则表达式来匹配参数--


太棒了,谢谢!唯一不起作用的是开关。必须使用path=“/products/page/:page(\d+)”然后使用error redirect path=“*”,它现在可以工作了。
 componentDidMount() {    
      const { page} = this.props.match.params;
      this.setState({currentPage:page});
      const { onFetchData, prodPerPage, filters } = this.props;
      onFetchBooks(prodPerPage, currentPage, filters);
      
    }
<Switch>
    <Route exact path="/products/page/:page(\\d+)" component={ProductsPage}/>
    <Route exact path="/products/page/:page(\\w+)" component={ErrorRedirectPage}/>
</Switch>