简体   繁体   English

当我尝试在新选项卡中加载页面时,React Router 重定向到 BASE_URL

[英]React Router redirects to BASE_URL when I try to load a page in a new tab

I have been working on a react project and I ran into a problem about 4 days ago.我一直在做一个反应项目,大约 4 天前我遇到了一个问题。 When I try to open a link in a new tab, it redirects to the home/BASE url.当我尝试在新选项卡中打开链接时,它会重定向到主页/BASE url。 Please I need assistance fixing the bug.请帮助我修复错误。

render route method渲染路由方法

export const renderRoutes = (routes = []) => (
  <Suspense fallback={<Loader />}>
    <Switch>
      {routes.map((route, i) => {
        const Guard = route.guard || Fragment;
        const Layout = route.layout || Fragment;
        const Component = route.component;

        return (
          <Route
            key={i}
            path={route.path}
            exact={route.exact}
            render={(props) => (
              <Guard>
                <Layout>
                  {route.routes
                    ? renderRoutes(route.routes)
                    : <Component {...props} />}
                </Layout>
              </Guard>
            )}
          />
        );
      })}
    </Switch>
  </Suspense>
);

来宾路线图

管理员路由的图片

GuestGuard访客卫士

const GuestGuard = (props) => {
  console.log(props, BASE_URL)
  if (props.isLoggedIn) {
    console.log(BASE_URL)
    return <Redirect to={BASE_URL} />;
  }

  return (
    <React.Fragment>
      {props.children}
    </React.Fragment>
  );
};

GuestGuard.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired
}

const mapStateToProps = (state) => ({
  isLoggedIn: state.auth.isLoggedIn
})

export default connect(mapStateToProps, )(GuestGuard);

AuthGuard AuthGuard

const AuthGuard = ({ children, isLoggedIn }) => {
    // console.log(children, 393)
    if (!isLoggedIn) {
        return <Redirect to="/auth/signin-1" />;
    }
    console.log("LOGGED IN", children.props)
    return (
        <React.Fragment>
            {children}
        </React.Fragment>
    );
};

AuthGuard.propTypes = {
    isLoggedIn: PropTypes.bool.isRequired
  }

const mapStateToProps = (state) => ({
    isLoggedIn: state.auth.isLoggedIn
})

export default connect(mapStateToProps, )(AuthGuard);

App (the provider is from react-redux)应用程序(提供者来自 react-redux)

const App = () => {
  useEffect(() => {
    store.dispatch(init());
  }, [])
  return (
    <Provider store={store}>    
        <Router basename={BASENAME}>          
          <React.Fragment>
            {renderRoutes(routes)}            
          </React.Fragment>
        </Router>
    </Provider>
  );
};

export default App;

init method called in the useEffect在 useEffect 中调用的 init 方法

export const init = () => (dispatch) => {
    try {
      const serviceToken = window.localStorage.getItem('serviceToken');        
      if (serviceToken) {
        setSession(serviceToken);
        axios.get('http://localhost:8000/api/auth/user', tokenConfig())
        .then(response => {         
          const user = response.data;
          dispatch({
            type: ACCOUNT_INITIALISE,
            payload: {
              isLoggedIn: true,
              user
            }
          })
        }).catch(err=>{
          dispatch({
            type:LOGOUT
          })
        })
      } else {
        dispatch({
          type: ACCOUNT_INITIALISE,
          payload: {
            isLoggedIn: false,
            user: null
          }
        });
      }
    } catch (err) {
      console.error(err);
      dispatch({
        type: ACCOUNT_INITIALISE,
        payload: {
          isLoggedIn: false,
          user: null
        }
      });
    }
  };

store (in the same dir as App.js)商店(在与 App.js 相同的目录中)

import {createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducers/index'

const initialState = {};

const middleware = [thunk];

const store = createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(...middleware),
      window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
  );

export default store;

auth reducer授权减速器

const initialState = {
  isLoggedIn: false,
  isInitialised: false,
  user: null
};
  
export default function (state = initialState, action) {
  switch (action.type) {
    case ACCOUNT_INITIALISE: {
        const { isLoggedIn, user } = action.payload;
        return {
            ...state,
            isLoggedIn,
            isInitialised: true,
            user
        };
    }
    case LOGIN: {
        const { user } = action.payload;
        return {
            ...state,
            isLoggedIn: true,
            user
        };
    }
    case LOGOUT: {
        localStorage.removeItem('serviceToken');
        return {
            ...state,
            isLoggedIn: false,
            user: null
        };
    }
    default: {
        return { ...state };
    }
}
  }

I think you need to debug the application flow here.我认为您需要在此处调试应用程序流程。 Below appears to be root cause, When link opens in new tab, it is protected by authGuard and the "init method called in the useEffect" is calling api asynchronously.下面似乎是根本原因,当链接在新选项卡中打开时,它受 authGuard 保护,并且“在 useEffect 中调用的 init 方法”正在异步调用 api。 So authGuard gets isloggedIn false the first time and redirects to "/auth/signin-1".所以 authGuard 第一次得到 isloggedIn false 并重定向到“/auth/signin-1”。 Meantime, isloggedIn sets as true and guestGuard redirects to Login page.同时,isloggedIn 设置为 true,guestGuard 重定向到登录页面。

You have below option here: Do not load your router unless you get response from api.您在此处有以下选项:除非您收到 api 的响应,否则不要加载您的路由器。 Display a loader while you get response.在收到响应时显示加载程序。

Hope you get the bug here and this answer helps you to fix same.希望你在这里得到这个错误,这个答案可以帮助你解决同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果我尝试在新标签页中复制并粘贴网址,React Router会显示404 - React Router gives 404 if I try to copy and paste url in new tab React Router的HashRouter重定向到 <base> 标签网址 - React Router's HashRouter redirects to <base> tag url 当我尝试通过手动更改 url 进行导航时,React App 重定向到路由“/” - React App redirects to route “/” when I try to navigate by changing url manually React 路由器将我重定向到 Hash 路由器,而不是返回到基础 url - React router redirects me to Hash Router instead of going back to the base url 反应路由器更改 URL,但视图没有改变,但是如果我在 url 位于浏览器选项卡上时按 Enter - React Router Changes URL, but view does't change, but if i press enter when the url is on the browser tab it does 在新标签页/页面中打开路由,并在React Router 4中保持某些状态 - Open a route in new tab/page and carry some state in react router 4 反应路由器 - 在新选项卡上打开链接并重定向到主页 - React Router - Open Link on new Tab and Redirect to Home Page 反应路由器基本URL不起作用 - React router base url not working 将路由器链接反应到新标签 - React Router Link to New Tab 当我尝试使用react-router-dom单击同一页面的同一链接时,最大更新深度超出了React - Maximum update depth exceeded React when I try to click on the same link for the same page with react-router-dom
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM