服务器端重定向与ReactJs

时间:2018-01-30 11:44:55

标签: reactjs express redirect react-router server-side

我正在尝试为某些页面发出服务器端重定向,以解决SEO问题。我试图解决的问题是我的某些网页会通过谷歌获取索引,因此如果它们被删除或脱机,我们希望将它们重定向到不同的页面而不是显示404.实现此类重定向的最佳方法是什么使用服务器端的React Router(express.js)?

3 个答案:

答案 0 :(得分:0)

你应该有一个应该定义路由规则的组件,如下所示:

<Router>
 <Switch>
      <Route path='/login' component= {LoginPage}/>
       ......
 </Switch>
<Router>

我要说的是你应该定义一个定义重定向url的包装器:

      var redirectToUrl = get url from your logic here;
      var urlComponent = '';
      if ( redirectToUrl )
      {
        urlComponent = <Redirect to={listing}/>;
      }

现在将此添加到您的网址处理页面:

<Router>
    <div>
      {urlComponent}
     <Switch>
          <Route path='/login' component= {LoginPage}/>
           ......
     </Switch>
</div>
    <Router>

答案 1 :(得分:0)

const redirect = (a,replace) => {
if(a.params.splat == "page1")
    replace("/page2")
}
<Route path="*" ... onEnter={redirect}/>

在server.js中

match(...,(error, redirectLocation, renderProps) => { 
   ... else if (redirectLocation) { res.redirect(302,`${redirectLocation.pathname}${redirectLocation.search}`...);

答案 2 :(得分:-1)

如果您使用的是React Router 4,则可以在页面组件中添加Redirect组件,以重定向已死的页面。 示例:假设组件尝试从API获取对象但获得了离线响应并将其存储在组件状态中:

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';

export default class PageComponent extends Component {

    // ... other stuff

    render() {
        if (this.state.page_offline) {
            return (<Redirect to="/some-page-for-offline-data" />);
        }

        return (...); // normal page render
    }

}