【问题标题】:foward to a specific url with react-router使用 react-router 转发到特定的 url
【发布时间】:2016-09-27 11:58:29
【问题描述】:

在我的 React-router-redux-redial 应用程序中,我们可以使用两个 url:

  • /accountId
  • /accountId/语言

语言是可选的。
当没有设置语言参数时,我们必须强制使用“fr”语言。
react-router 是否有可能自动将“/accountId”转发到“/accountId/fr”?

IndexRoute 没有任何路径属性来强制 url 并且重定向功能不适合我们的需求,出于某些 SEO 原因,我们希望在 url 中看到“/accountId/fr”。

我试图在我的 LandingCmp 的渲染函数中进行 dispatch(push("/accountId/fr")) 但它不起作用。

我们使用重拨 (@provideHooks) 来确保在服务器端进行干净的预渲染。

这是我当前的路由表:

<Route path='/'>
  <Route path="error" component={ErrorsCmp} />
  <Route path=":accountId">
    <Route path=":langue">
      <IndexRoute component={LandingCmp} />
    </Route>
    <IndexRoute component={LandingCmp} />
  </Route>
</Route>

我们使用以下依赖项: - “react-router-redux”:“4.0.5” - “反应路由器”:“2.7.0”

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您可以导入 browserHistory,然后使用它来动态推送到不同的路由。所以你可以检查params来看看accountId后面是否有参数,如果没有你可以使用:

    browserHistory.push("/accountId/fr");
    

    并导入 browserHistory:

    import {browserHistory} from 'react-router';
    

    【讨论】:

      【解决方案2】:

      您可以在componentWillMount 生命周期方法中使用withRouter 包装器中的push url,该包装器在较新版本的 React Router(自版本 2.4.0 起)中可用。更多信息:https://github.com/ReactTraining/react-router/blob/master/docs/API.md#withroutercomponent-options

      结构可能如下所示:

      import { withRouter } from 'react-router';
      
      class App extends React.Component {
        componentWillMount() {
          this.props.router.push('/accountId/fr');
        }
      
        render() {
        // your content
        }
      }
      
      export default withRouter(App);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-21
        • 2021-08-18
        • 2016-09-06
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 2020-03-21
        • 2021-04-24
        相关资源
        最近更新 更多