Jos*_*man 4 reactjs ionic-framework ionic5
我对 React 和 Ionic 还很陌生。我试图完成的是创建一条“受保护的路线”。我创建一个简单的上下文,名为AuthContext:
import { createContext, Dispatch } from 'react';
/**
* Context interface for AuthAuthentication/Authorization
*
* @property isAuthenticated
* @property dispatch
*
* @interface
*/
interface AuthDefaultContext {
isAuthenticated: boolean;
dispatch: Dispatch<any>
}
/**
* Authentication/Authorization context for managing
* authenticating/ed and authorizing/ed users
*/
export const AuthContext = createContext<AuthDefaultContext>({
isAuthenticated: false,
dispatch: () => {}
});
Run Code Online (Sandbox Code Playgroud)
和FunctionalComponent称为ProtectedRoute:
interface ProtectedRouteProps {
ProtectedComponent: FunctionComponent,
routePath: string
}
export const ProtectedRoute: FunctionComponent<ProtectedRouteProps> = ({ ProtectedComponent, routePath }) => {
useEffect(() => {
console.log(`loading protected route '${routePath}' with component ${ProtectedComponent.name}`)
}, [ProtectedComponent, routePath] );
return (
<AuthContext.Consumer>
{
({ isAuthenticated }) => (
<Route path={ routePath } render={ () => isAuthenticated ? <ProtectedComponent/> : <Redirect to="/login" /> }/>
)
}
</AuthContext.Consumer>
);
}
Run Code Online (Sandbox Code Playgroud)
在我的主应用程序组件中,我将其包裹IonReactRouter在里面,AuthContext.Provider如下所示:
<IonApp>
<AuthContext.Provider value={{ isAuthenticated: authenticated, dispatch: dispatch }}>
<IonReactRouter>
<IonRouterOutlet>
<Route path="/login" component={ Login } exact={ true } />
<ProtectedRoute routePath="/welcome" ProtectedComponent={ Welcome }/>
<ProtectedRoute routePath="/search" ProtectedComponent={ Dummy }/>
</IonRouterOutlet>
</IonReactRouter>
</AuthContext.Provider>
</IonApp>
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,上面的方法对于常规路由和第一个 ProtectedRoute 工作正常,但不起作用/search/。浏览器 url 中的 uri 路径发生更改,/search但虚拟组件不会呈现。
我注意到,如果你交换<IonReactRouter>并<IonRouterOutlet>像这样:
<IonRouterOutlet>
<IonReactRouter>
.....
</IonReactRouter>
</IonRouterOutlet>
Run Code Online (Sandbox Code Playgroud)
所有路线都有效,但您会失去IonRouterOutlet. Ionics 网站上的导航文档有包装IonReactRouter,IonRouterOutlet所以我假设这是正确的实现。
如果我将ProtectedRoute's 更改为标准反应,Route则所有路线都可以与动画一起正常工作。所以问题必须出在我的ProtectedRoute组件实现上,我只是无法弄清楚。非常感激任何的帮助。谢谢你!
更新:
我仍然没有找到解决此问题的方法,因此我删除了 IonRouterOutlet,这似乎是根本原因。这样做时,一切都会按预期进行。我在 Ionic 论坛上发布了这个问题,因此当/如果我得到答案时,我会将其发布在这里。
谢谢,
IonRouterOutlet 期望其子级是 Routes 或“Route like”,这意味着子级需要具有与 Route 相同的基本 props。
因此,对于您的 ProtectedRoute,如果您将传入的 props 重命名routePath为path和ProtectedComponent,它应该可以工作component。
我从这里的代码开始整理了一个工作示例存储库:https ://github.com/elylucas/ionic-react-protected-route
让我知道这是否有帮助。
谢谢