反应路由器DOM:路由和路由器根本不工作

我是比较新的RESPECT,我尝试使用REACTION-ROUTER-DOM进行重定向,我按照文档做了所有的工作,但我的代码似乎不起作用。我收到一个关于没有找到元素的错误,我不知道是什么导致了它。此外,我只是尝试使用地址栏访问页面,而不是现在使用任何按钮或链接。

错误

Matched leaf route at location "/" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.

与/Register相同的错误

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Route, BrowserRouter as Router, Routes } from 'react-router-dom';
import Register from "./components/Register";

ReactDOM.render( 
  <Router>
    <React.StrictMode>
      <Routes>
        <Route exact path="/register" component={Register} />
        <Route exact path="/" component={App} />
      </Routes>
      <App />
    </React.StrictMode>
  </Router>,
  document.getElementById('root')
);

reportWebVitals();

App.js

import { Component } from 'react';

class App extends Component {
  render(){
    return (
      <div>
        HELLO WORLD
      </div>
    );
  }
}


export default App;

Register.js

import { useState } from "react";
import { useNavigate } from "react-router-dom";

export default function Register(){
    const history = useNavigate();
    const initialFormData = Object.freeze({
          email: '',
          password: '',
      });

      const [formData, updateFormData] = useState(initialFormData);

    const handleChange = (event) => {
      updateFormData({
              ...formData,
              // Trimming any whitespace
              [event.target.name]: event.target.value.trim(),
          });
    }

    const handleSubmit = (event) => {
      event.preventDefault();
      console.log(event.target.email.value);
      console.log(event.target.password.value);
    }

    return (
      <form onSubmit={handleSubmit}>
        <div>
          <label>
            Email: 
            <input type="text" value={formData.email} name="email" onChange={handleChange} />
          </label>
        </div>
        <div>
          <label>
            Password: 
            <input type="text" value={formData.password} name="password" onChange={handleChange}/>
          </label>
        </div>
        <input type="submit" value="Submit" />
      </form>
  );
}


解决方案

您没有正确呈现工艺路线组件。它们应该在element道具上呈现为JSX,而不是对组件的引用。这是react-router-dom版本5和6之间的一个突破性变化。另请注意,Route组件也不再具有exact道具,它们现在始终完全匹配。

ReactDOM.render( 
  <Router>
    <React.StrictMode>
      <Routes>
        <Route path="/register" element={<Register />} />
        <Route path="/" element={<App />} />
      </Routes>
      <App />
    </React.StrictMode>
  </Router>,
  document.getElementById('root')
);

相关文章