[英]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.