React 中 Auth0Provider 和 (Browser)Router 之间的嵌套顺序
Order of nesting between Auth0Provider and (Browser)Router in React
我有一些关于 Auth0 与 React 集成的问题,我无法在官方论坛上找到答案 -
SDK docs/samples 提到 Auth0Provider
应该包装 React Router
元素
(https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#1-protecting-a-route-in-a-react-router-dom-app):
<Auth0Provider
domain="YOUR_AUTH0_DOMAIN"
clientId="YOUR_AUTH0_CLIENT_ID"
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
{/* Don't forget to add the history to your router */}
<Router history={history}>
<Switch>
<Route path="/" exact />
<ProtectedRoute path="/profile" component={Profile} />
</Switch>
</Router>
</Auth0Provider>
这迫使我们(SDK 用户)手动创建 history
对象,然后将其传递给 Auth0Provider
和 Router
,这样我们就可以在身份验证重定向上操纵相同版本的历史记录(同样,如文档中所述)。
似乎可以颠倒嵌套顺序,让 Auth0Provider
被默认 BrowserRouter
包裹起来。这允许我们在 Auth0Provider
上创建自定义包装器,并通过 useHistory
挂钩访问内置历史对象:
export const AppAuthentication: React.FC = (props) => {
const history = useHistory();
const onRedirectCallback = (appState: AppState) => {
history.replace(appState?.returnTo || window.location.pathname);
};
return (
<Auth0Provider
domain={...}
clientId={...}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
{props.children}
</Auth0Provider>
);
};
现在使用更简单了-
const App: React.FC = () => {
return (
<Router>
<AppAuthentication>
....
</AppAuthentication>
</Router>
);
};
我进行了一些快速测试,似乎运行良好。是否有理由 不 遵循这种方法?这似乎比官方指南推荐的维护自己的历史副本要干净得多。
我从 Auth0 那里得知这种方法很好,但不幸的是我还没有从他们那里得到任何官方信息(还没有?)。
我有一些关于 Auth0 与 React 集成的问题,我无法在官方论坛上找到答案 -
SDK docs/samples 提到 Auth0Provider
应该包装 React Router
元素
(https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#1-protecting-a-route-in-a-react-router-dom-app):
<Auth0Provider
domain="YOUR_AUTH0_DOMAIN"
clientId="YOUR_AUTH0_CLIENT_ID"
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
{/* Don't forget to add the history to your router */}
<Router history={history}>
<Switch>
<Route path="/" exact />
<ProtectedRoute path="/profile" component={Profile} />
</Switch>
</Router>
</Auth0Provider>
这迫使我们(SDK 用户)手动创建 history
对象,然后将其传递给 Auth0Provider
和 Router
,这样我们就可以在身份验证重定向上操纵相同版本的历史记录(同样,如文档中所述)。
似乎可以颠倒嵌套顺序,让 Auth0Provider
被默认 BrowserRouter
包裹起来。这允许我们在 Auth0Provider
上创建自定义包装器,并通过 useHistory
挂钩访问内置历史对象:
export const AppAuthentication: React.FC = (props) => {
const history = useHistory();
const onRedirectCallback = (appState: AppState) => {
history.replace(appState?.returnTo || window.location.pathname);
};
return (
<Auth0Provider
domain={...}
clientId={...}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
{props.children}
</Auth0Provider>
);
};
现在使用更简单了-
const App: React.FC = () => {
return (
<Router>
<AppAuthentication>
....
</AppAuthentication>
</Router>
);
};
我进行了一些快速测试,似乎运行良好。是否有理由 不 遵循这种方法?这似乎比官方指南推荐的维护自己的历史副本要干净得多。
我从 Auth0 那里得知这种方法很好,但不幸的是我还没有从他们那里得到任何官方信息(还没有?)。