React Router v4 中的参数无法正常工作

Params in React Router v4 is not working correctly

我知道这个问题已经被问过很多次了,我也看过答案,但我并没有走得太远。我正在创建一些样板(因为我厌倦了一遍又一遍地编写相同的基本代码)但我无法通过 RR v4;具体来说,params

这个样板非常简单。现在,我正在使用 RR4 导航到 posts,但是,即使我使用不同的 slug 路由到 post,它总是 returns 相同的 post。 (first-post)。关于如何正确导航的任何建议?我认为文档在 params 方面并不太好。这是回购协议:

https://github.com/boilerstrapper/react-boilerstrap

更新:

这是一些代码:

components/App/index.js
// ...imports


export const App = () => {
  return (
    <div>
      <Nav />

      <Switch>
        <Route exact path='/' component={Login} />
        <Route exact path='/posts' component={PostList} />
        <Route exact path='/posts/:slug' component={PostListItem} />
        <Route exact path='/products' component={ProductList} />
        <Route exact path='/products/:slug' component={ProductListItem} />
        <Route exact path='/login' component={Login} />
        <Route component={NotFound} />
      </Switch>

    </div>
  );
}

因此,当您更改 url 中的参数 :slug 时,您只是将作为 prop (props.match.params.slug) 传递的内容更改为您拥有的容器组件,但事实并非如此销毁现有的渲染组件并重建它(因为它是同一个组件)。这意味着在您对数据发出 http 请求时不会再次调用构造函数。

为了解决这个问题,我做了类似以下的事情:

  componentWillMount() {
    this.loadEvents();
  }
  componentWillReceiveProps(nprops) {
    this.loadEvents(nprops.match.params.orgId);
  }
  loadEvents(orgId = this.props.match.params.orgId) {
    axios.get(`/_api/org/events?org=${orgId}`)
      .then(res => {
        this.setState({ events: res.data });
      })
      .catch(alert);
  }

以便在参数变化时请求数据!

所以,我真的找到了答案。我在 API:

中写了这个

const slug: string = req.body.slug

而不是:

const slug: string = req.params.slug