我有一个使用Apollo(react-apollo)以及AWS AppSync React的React应用。我正在尝试使用文档中所述的Provider
组件包装我的React应用,将我的应用包装在withRouter
包中的react-router
中,以便我可以在成功注销和登录后重定向该应用。目前,我具有App.js
和index.js
的自举CRA结构
// index.js
import React from "react";
import ReactDOM from "react-dom";
import AppContainer from "./App";
import { LoadingScreen } from "./components";
import Amplify from "aws-amplify";
import AWSAppSyncClient from "aws-appsync";
import { Rehydrated } from "aws-appsync-react";
import { ApolloProvider } from "react-apollo";
Amplify.configure({
...
});
const client = new AWSAppSyncClient({
...
});
const WithProvider = () => (
<ApolloProvider client={client}>
<Rehydrated render={({ rehydrated }) => (rehydrated ? <AppContainer /> : <LoadingScreen />)}>
<AppContainer />
</Rehydrated>
</ApolloProvider>
);
ReactDOM.render(<WithProvider />, document.getElementById("root"));
// App.js
import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";
import { BrowserRouter, withRouter } from "react-router-dom";
import { hot } from "react-hot-loader";
import { Auth } from "aws-amplify";
import ScrollToTop from "./config/ScrollToTop";
import { Navbar } from "./components";
import Routes from "./config/routes";
class AppContainer extends Component {
static displayName = "AppContainer";
static propTypes = {
history: PropTypes.array
}
constructor(props) {
super(props);
this.state = {
isAuthenticated: false
};
}
componentDidMount() {
...
}
userHasAuthenticated = authenticated => {
...
}
handleLogout = async () => {
await Auth.signOut();
this.userHasAuthenticated(false);
window.location.replace("/");
}
render() {
const childProps = {
isAuthenticated: this.state.isAuthenticated,
userHasAuthenticated: this.userHasAuthenticated,
handleLogout: this.handleLogout
};
return (
<BrowserRouter>
<ScrollToTop>
{ !this.state.isAuthenticating &&
<Fragment>
<Navbar childProps={childProps} />
<Routes childProps={childProps} />
</Fragment>
}
</ScrollToTop>
</BrowserRouter>
);
}
}
export default withRouter(hot(module)(AppContainer));
尝试运行我的应用程序时,我得到You should not use <Route> or withRouter() outside a <Router>
-我尝试export default hot(module)(withRouter(AppContainer));
无济于事。
答案 0 :(得分:0)
汤姆
您是否使用Cognito用户池作为身份验证方法。如果是这样的话,我建议您使用aws-amplify,将带有身份验证器组件或withAuthenticator HOC的react应用包装起来非常简单。看看here