React Router Dom v6 - 带参数的元素让我觉得函数作为反应子项无效

React Router Dom v6 - element with parameters drives me to functions are not valid as a react child

我知道有很多关于这个主题的帖子,但我还没有找到一个将元素作为参数传递的帖子,而且我不知道如何在不声明函数的情况下进行操作。 我不明白为什么反应会告诉我这个错误,因为我认为它只是在调用的反应组件不包含反应组件时才这么说 structure/elements/requirements.

我的 MainComponent.js 代码如下:(我将参数传递给带有 const DishWithId 的路径 /menu/:dishId)

import {Navbar,NavbarBrand} from 'reactstrap';
import React, { Component } from 'react';
import { useState } from "react";
import Menu from './MenuComponent';
import Footer from './FooterComponent';
import {DISHES} from '../shared/dishes'
import Dishdetail from './DishdetailComponent';
import Home from './HomeComponent';
import Contact from './ContactComponent'
import {Routes,Route,Navigate} from 'react-router-dom';
import Header from './HeaderComponent'
import {COMMENTS} from '../shared/comments';
import {LEADERS} from '../shared/leaders';
import {PROMOTIONS} from '../shared/promotions';
class Main extends Component {
  constructor (props){
    super (props);
    this.state = {dishes: DISHES, comments: COMMENTS, promotions: PROMOTIONS, leaders: LEADERS};
  }


  render(){
    const shouldRedirect=true;

    const HomePage=()=>{
    return (
        <Home dish={this.state.dishes.filter((dish)=>dish.featured)[0]}
              promotion={this.state.promotions.filter((promotion)=>promotion.featured)[0]}
              leader={this.state.leaders.filter((leader)=>leader.featured)[0]}
        />
    );
  }
  const DishWithId=({match})=>{

      return (
          <Dishdetail dish={this.state.dishes.filter((dish) => dish.id === parseInt(match.params.dishId, 10))[0]}
                      comments={this.state.comments.filter((comment) => comment.dishId === parseInt(match.params.dishId, 10)[0])}/>

      );
    
    }

  return (<div className="App">
    <Header />
      <Routes>
        <Route exact path='/menu' element={<Menu dishes={this.state.dishes}/> }/>
        <Route path="/menu/:dishId" element={DishWithId}/>
        <Route path='/home' element={<HomePage/>}/>
        <Route exact path='/contactus' element={<Contact/>}/>
        <Route path='/' element={
            shouldRedirect ? (<Navigate replace to="/home" />) : (<HomePage />)
          }/>
      </Routes>

    <Footer/>

  </div>);
}
}
export default Main;

当我访问 http://localhost:3000/ 时出现错误menu/0 我尝试使用 render() 但我没能成功。 请注意,此代码应该与以前版本的 React 一起使用,其中组件代替了元素(它来自 mooc)...

您需要更改路线

<Route path="/menu/:dishId" element={DishWithId}/>

收件人:

<Route path="/menu/:dishId" element={<DishWithId />}/>

并更新您的 DishWithId 以使用 useParams 挂钩获取 dishId,例如:

const DishWithId=({match})=>{
  const { dishId } = useParams()

  return (
      <Dishdetail dish={this.state.dishes.filter((dish) => dish.id === parseInt(dishId, 10))[0]}
                  comments={this.state.comments.filter((comment) => comment.dishId === parseInt(dishId, 10)[0])}/>

  );

}