首页 > 解决方案 > React Private Route Redirect 不适用于 Asp.net 核心

问题描述

我在 vs 2017 中使用 Asp.Net Core 和 typescript/webpack/react 创建了一个网站。

基本上,我的网站有 3 个页面:主页索引页面、登录页面和仪表板。主页是渲染 React 应用程序的主页。

如果用户登录,Dashboard 组件将被呈现,如果没有,则登录组件将呈现在 Home Index 视图中。

下面是我列出路线的主要应用程序:

export class App extends React.Component<{}, {}> {
  constructor(props) {
    super(props);
  }

  public render() {
    return (
      <div >
        <Route exact path="/" component={Login} />
        <Route exact  path="/login" component={Login} />
        <Layout>
          <PrivateRoute exact path="/dashboard" component={Dashboard} />
        </Layout>
      </div>
    );
  }
}

PrivateRoute 就像:

export const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    localStorage.getItem('user') ?
      <Component {...props} /> : 
      <Redirect to={{ 
        pathname: '/login', 
        state: { from: props.location } 
      }} />
    )}/>
)

这就像未登录时一样工作,然后它会返回登录组件(在主页索引内)url。但问题是,如果我只是从浏览器 (localhost:1234/login) 刷新该页面,那么它会尝试/login在 MVC 路由中找到它,所以它会给我如下错误:

在此处输入图像描述

如果我从 PrivateRoute 中删除重定向,那么它可以正常工作。所以我认为问题在于 MVC 路由发生在重定向。

标签: reactjsasp.net-corewebpackreact-router

解决方案


推荐阅读