简体   繁体   English

即使尝试使用 Routes 和 Router,路由也无法正常工作

[英]Routes not working in react even when trying to use Routes and Router

I'm following this tutorial: https://ibaslogic.com/routing-with-react-router/我正在关注本教程: https://ibaslogic.com/routing-with-react-router/

When I render the page, I recieve this error当我呈现页面时,我收到此错误

Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.
    at invariant (bundle.js:61876)
    at Route (bundle.js:62025)
    at renderWithHooks (bundle.js:23504)
    at mountIndeterminateComponent (bundle.js:26266)
    at beginWork (bundle.js:27465)
    at HTMLUnknownElement.callCallback (bundle.js:12454)
    at Object.invokeGuardedCallbackDev (bundle.js:12503)
    at invokeGuardedCallback (bundle.js:12563)
    at beginWork$1 (bundle.js:32305)
    at performUnitOfWork (bundle.js:31141)

I've tried to wrap the Route in Routes as the warning suggests.正如警告所暗示的那样,我试图将Route包装在Routes中。 I still get an error that I need Router which I already have.我仍然收到一个错误,我需要我已经拥有的Router I've also tried the suggestions here react-router, routes not working without success我也试过这里的建议react-router,路线没有成功

Here is my js component file where the error is taking place:这是发生错误的我的js组件文件:

import React, { useState, useEffect } from "react"
import TodosList from "./TodosList";
import Header from "./Header";
import InputTodo from "./InputTodo";
import { v4 as uuidv4 } from "uuid";
import "./App.css"
import { Route, Switch } from "react-router-dom"

const TodoContainer = () => {
  const [todos, setTodos] = useState(getInitialTodos())

  const handleChange = id => {
    setTodos(prevState =>
      prevState.map(todo => {
        if (todo.id === id) {
          return {
            ...todo,
            completed: !todo.completed,
          }
        }
        return todo
      })
    )
  }

  const delTodo = id => {
    setTodos([
      ...todos.filter(todo => {
        return todo.id !== id
      }),
    ])
  }

  const addTodoItem = title => {
    const newTodo = {
      id: uuidv4(),
      title: title,
      completed: false,
    }
    setTodos([...todos, newTodo])
  }

  const setUpdate = (updatedTitle, id) => {
    setTodos(
      todos.map(todo => {
        if (todo.id === id) {
          todo.title = updatedTitle
        }
        return todo
      })
    )
  }

  // useEffect(() => {
  //   console.log("test run")
  
  //   // getting stored items
  //   const temp = localStorage.getItem("todos")
  //   const loadedTodos = JSON.parse(temp)
  
  //   if (loadedTodos) {
  //     setTodos(loadedTodos)
  //   }
  // }, [])

  function getInitialTodos() {
    // getting stored items
    const temp = localStorage.getItem("todos")
    const savedTodos = JSON.parse(temp)
    return savedTodos || []
  }

  useEffect(() => {
    // storing todos items
    const temp = JSON.stringify(todos)
    localStorage.setItem("todos", temp)
  }, [todos])

  

  return (
    <Route path="/">
      <div className="container">
        <div className="inner">
          <Header />
          <InputTodo addTodoProps={addTodoItem} />
          <TodosList
            todos={todos}
            handleChangeProps={handleChange}
            deleteTodoProps={delTodo}
            setUpdate={setUpdate}
          />
        </div>
      </div>
    </Route>
  )
}

export default TodoContainer

Here is my index.js:这是我的 index.js:

import React from "react"
import ReactDOM from "react-dom"
//component file
import TodoContainer from "./functionBased/components/TodoContainer"
import { BrowserRouter as Router } from "react-router-dom"

//stylesheet
import "./functionBased/App.css"

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <TodoContainer />
    </Router>
  </React.StrictMode>,
  document.getElementById("root")
)

I'm unsure how to make Route work.我不确定如何使Route工作。 Thank you谢谢

Not sure I understand the problem correctly but maybe try in the index.js to change不确定我是否正确理解了问题,但也许可以尝试在 index.js 中进行更改

<TodoContainer />

with:和:

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

also remember to import Route from react-router-dom还记得从 react-router-dom 导入 Route

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

This blogpost by Esteban Herrera gives a good example on how to use react router. Esteban Herrera 的这篇博文给出了如何使用 React 路由器的一个很好的例子。 https://blog.logrocket.com/react-router-dom-tutorial-examples/ https://blog.logrocket.com/react-router-dom-tutorial-examples/

I think you need to do something like that:我认为你需要做这样的事情:

  • remove Route tag from your component folder从组件文件夹中删除 Route 标记
  • add Route tag to your index.js file like that像这样将 Route 标记添加到您的 index.js 文件中
import {BrowserRouter as Router, Route} from 'react-router-dom';

...

 <Router>
     <Route exact path="/" element={<TodoContainer />}/>
 </Router>

You are supposed to declare your Route in the Routes component.您应该在Routes组件中声明您的Route So you should first wrap the TodoContainer in the Routes component and then put the element you want to render in the element property of the Route component所以你应该先将TodoContainer包裹在Routes组件中,然后将要渲染的元素放入Route组件的element属性中

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <Routes>
        <Route path="/" element={<TodoContainer />}/>
      </Routes>
    </Router>
  </React.StrictMode>,
  document.getElementById("root")
)

Then, you don't need to handle the routing anymore in the TodoContainer然后,您无需再在TodoContainer中处理路由

Take a look at the documentation to learn more about routing (this is the react router v6 here)查看文档以了解有关路由的更多信息(这里是 react router v6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM