[英]How to set default Route in React Router?
I have React Component:我有 React 组件:
import { useState, useEffect } from "react";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";
import {
collection,
getDocs,
} from "https://www.gstatic.com/firebasejs/9.6.0/firebase-firestore.js";
import { onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-auth.js";
import { db, auth } from "../firebaseConfig";
import Hotels from "./Hotels/Hotels";
import CreateReview from "./CreateReview/CreateReview";
import MyAccount from "./MyAccount/MyAccount";
import WelcomePage from "./WelcomePage/WelcomePage";
import NavBar from "./NavBar/NavBar";
function MainPage() {
const [hotels, setHotels] = useState([]);
const [authentication, setAuthentication] = useState(false);
async function fetchHotels() {
const _hotels = [];
const querySnapshot = await getDocs(collection(db, "reviews"));
querySnapshot.forEach((doc) => {
_hotels.push(doc.data());
});
console.log("Data is fetched!");
setHotels(_hotels);
}
useEffect(() => {
fetchHotels();
}, []);
function isAuthenticated() {
onAuthStateChanged(auth, (user) => {
if (user) {
setAuthentication(true);
console.log("User is signed in");
} else {
setAuthentication(false);
console.log("User is signed out");
}
});
}
useEffect(() => {
isAuthenticated();
}, []);
return (
<div>
{authentication ? (
<BrowserRouter>
<NavBar />
<div className="container">
<Routes>
<Route
exact
path="/CreateReview"
element={<CreateReview />}
></Route>
<Route
exact
path="/Hotels"
element={<Hotels hotels={hotels} />}
></Route>
<Route exact path="/MyAccount" element={<MyAccount />}></Route>
</Routes>
</div>
</BrowserRouter>
) : (
<div className="container">
<WelcomePage />
</div>
)}
</div>
);
}
export default MainPage;
I want the component to be displayed when I launch the application and reload the page我希望在启动应用程序并重新加载页面时显示该组件
Reloading or restarting now opens the last viewed component.现在重新加载或重新启动会打开上次查看的组件。 Perhaps I need to import something else from the react-router library?也许我需要从 react-router 库中导入其他东西?
I think the library has some solution, but I didn't find it on the inte.net.我认为图书馆有一些解决方案,但我没有在 inte.net 上找到它。 How can this problem be solved?如何解决这个问题?
Add this Route
as the last route inside Routes
.将此Route
添加为Routes
中的最后一条路线。
<Route path="*" element={DefaultComponent} />
Replace DefaultComponent
with whatever is your default component.将DefaultComponent
替换为您的默认组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.