我正在开发一个应用程序,我使用Firebase作为应用程序的认证系统,当我试图实现应用程序的路由时,我开始得到上述标题错误。
我使用withouter函数来封装我的App组件。
所以我的App.tsx文件的代码如下:import React, { FC, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
Route,
Switch,
useHistory,
withRouter,
BrowserRouter as Router,
} from "react-router-dom";
import "./App.css";
import Header from "./components/sections/Header";
import SignUp from "./components/pages/SignUp";
import SignIn from "./components/pages/SignIn";
import ForgotPassword from "./components/pages/ForgotPassword";
import Homepage from "./components/pages/Homepage";
import Dashboard from "./components/pages/Dashboard";
import PrivateRoute from "./components/auth/PrivateRoute";
import PublicRoute from "./components/auth/PublicRoute";
import Loader from "./components/UI/Loader";
import firebase from "./firebase/config";
import {
getUserById,
setLoading,
setNeedVerification,
} from "./store/actions/authActions";
import { RootState } from "./store";
const App: FC = () => {
const dispatch = useDispatch();
const { loading } = useSelector((state: RootState) => state.auth);
let history = useHistory();
// Check if user exists
// App.tsx
useEffect(() => {
dispatch(setLoading(true));
const unsubscribe = firebase.auth().onAuthStateChanged(async (user) => {
if (user) {
await dispatch(getUserById(user.uid));
if (user.emailVerified) {
history.push("/homepage");
} else {
history.push("/signin");
dispatch(setNeedVerification());
}
}
dispatch(setLoading(false));
});
return () => {
unsubscribe();
};
});
if (loading) {
return <Loader />;
}
function Routes() {
return (
<Switch>
<PublicRoute path="/signup" component={SignUp} exact />
<PublicRoute path="/signin" component={SignIn} exact />
<PublicRoute path="/forgot-password" component={ForgotPassword} exact />
<PrivateRoute path="/dashboard" component={Dashboard} exact />
<PublicRoute path="/homepage" component={Homepage} exact />
</Switch>
);
}
return (
<Router>
<Header />
<Routes />
</Router>
);
};
export default withRouter(App);
'所以我认为这必须与路由库的配置关联到应用程序的主组件中。
我错过了什么?
提前感谢!
App
是渲染Router
的组件,因此App
本身不能使用任何需要在React树中更高位置的Router
上下文的内容。
解决方案是将Router
移动到React树的更高位置,即将App
包裹在Router
中。一旦App
被Router
渲染,因为你正在使用useHistory
钩子,就不需要用withRouter
HOC来装饰。
应用
const App: FC = () => {
...
function Routes() {
return (
<Switch>
<PublicRoute path="/signup" component={SignUp} exact />
<PublicRoute path="/signin" component={SignIn} exact />
<PublicRoute path="/forgot-password" component={ForgotPassword} exact />
<PrivateRoute path="/dashboard" component={Dashboard} exact />
<PublicRoute path="/homepage" component={Homepage} exact />
</Switch>
);
}
return (
<>
<Header />
<Routes />
</>
);
};
export default App;
显示App
的索引。
import { BrowserRouter as Router } from "react-router-dom";
import App from '../App';
...
<Router>
<App />
</Router>