使用路由对 ReactJs 组件进行双重渲染

Double rendering for ReactJs component with Routes

在reactJs中,我曾经使用以下代码来声明路由:

<Route exact path="/" component={Home} />

但是我看到它变成了这个语法

<Route exact path="/" element={<Home />} />

问题是我有双重渲染,元素 Home 总是在当前组件之后渲染。

这是我的 App.js :

import React from 'react';
import './App.css';
import Header from './components/general-content/Header';
import Home from './components/home/Home';
import TablesTest from './components/tables/TablesTest';
import TablesTestResults from './components/tables/TablesTestResults.jsx';

import Footer from './components/general-content/Footer';
import Error from  './components/general-content/Error';
import ThemeContext from './components/context/ThemeContext';

import { BrowserRouter, Route, Routes } from 'react-router-dom';

function App() {

  const [theme, setTheme] = React.useState("Brazil");

  const themeContext = {
    theme: theme,
    updateTheme: setTheme
  };

  return (
      <div className="App">
          <ThemeContext.Provider value={themeContext} >
                  <div className={theme}>
                      <BrowserRouter>
                          <Header />
                              <Routes>
                                  <Route exact path="/" element={<Home />} />
                                  <Route path="/test" element={<TablesTest />} />
                                  <Route path="/test-results" element={<TablesTestResults />} />
                                  <Route path="/error" element={<Error />} />
                              </Routes> 
                              <Home />
                          <Footer />
                      </BrowserRouter>
                  </div>
          </ThemeContext.Provider>
      </div>
  );
}

export default App;

感谢您的支持!

您有一个错字:您应该删除 BrowserRouter 内部但 Route 外部的 Home 组件,如下所示:

<BrowserRouter>
    <Header />
    <Routes>
        <Route exact path="/" element={<Home />} />
        <Route path="/test" element={<TablesTest />} />
        <Route path="/test-results" element={<TablesTestResults />} />
        <Route path="/error" element={<Error />} />
    </Routes>
    // <Home /> You have to delete this component, it is not required
    <Footer />
</BrowserRouter>