React Typescript 错误:不变失败:您不应该><Router><在



我正在开发一个应用程序,我使用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中。一旦AppRouter渲染,因为你正在使用useHistory钩子,就不需要用withRouterHOC来装饰。

应用

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>

相关内容

  • 没有找到相关文章

最新更新