React Router v6 error: All component children of <Routes> must be a <Route> or <React.Fragment>

React Router v6 error: All component children of <Routes> must be a <Route> or <React.Fragment>

以下 React 路由代码可能在 React Router v5 中有效,但在 React Router v6 中出现以下错误

Error: [Player] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

是否可以更新 Routes/Route 代码,使其在 React Router v6 中运行?

function App() {
  // Some stuff here...

  const { players, offlinePlayers } = usePlayers();


  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
        <BrowserRouter>

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

                <Route path="/players">
                {players.map((player) => {
                    return (
                    <Route exact key={player.name} path={`/players/${player.name}`}>
                        <Player player={player} />
                    </Route>
                    );
                })}
                </Route>
            </Routes>  

        </BrowserRouter>
    </ThemeProvider>
  )

}

Player 组件应由 element 属性上的 Route 组件呈现,而不是 Route.

的子组件
<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/players">
      {players.map((player) => (
        <Route
          key={player.name}
          path={`/players/${player.name}`}
          element={<Player player={player} />}
        />
      ))}
    </Route>
  </Routes> 
</BrowserRouter>

您应该在其父路由中映射路由。 喜欢:

   <Route path="/players">
     {players.map((player) => (
         <Route exact key={player.name} path={`/players/${player.name}`}>
            <Player player={player} />
         </Route>
       );
     )}
   </Route>

但是,如果您想呈现动态播放器,则不要为此目的使用上述代码,因为如果您使用动态 player.name,这不是最佳方法。在您的代码中,您正在为每个玩家创建每条路线。 所以,使用下面的代码:

<Route path="/players">
   <Route exact path={":playerName"} element={<Player/>} />
</Route>

并且在 Player 组件中,从参数中提取 playerName,例如:

let { playerName } = useParams();