簡體   English   中英

如何解決“函數作為 React 子級無效”。 當我嘗試根據函數的輸出渲染組件時出錯?

[英]How to solve "Functions are not valid as a React child." error when I try to render a components based on the output of a function?

在應用程序的 App.js 文件中,我正在設置應用程序的路由。

這是我的 App.js 文件的代碼

import React, {useEffect} from "react";
import {Container} from '@material-ui/core';
import {BrowserRouter, Routes, Route, Navigate} from 'react-router-dom';
import { gapi } from 'gapi-script';
import Navbar from "./components/Navbar/Navbar";
import Home from './components/Home/Home';
import Auth from "./components/Auth/Auth";
import MealsPage from "./components/MealsPage/MealsPage";
import WorkoutDetails from "./components/WorkoutDetails/WorkoutDetails";

const App=()=>{
  const user=JSON.parse(localStorage.getItem('profile'));

    useEffect(() => {
        const start = () => {
          gapi.auth2.init({
            clientId: process.env.REACT_APP_GOOGLE_API_TOKEN,
            scope: ""
          })
        };
    
        gapi.load('client:auth2', start);
      })

     
    return(
        <BrowserRouter>
        <Container maxWidth="xl">
        <Navbar/>
        <Routes>
            <Route path="/" exact ={()=>{<Navigate to="/workouts"/>}}/>
            <Route path="/workouts" exact element={<Home/>}/>
            <Route path="/workouts/search" exact element={<Home/>}/>
            <Route path="/workouts/:id" element={<WorkoutDetails/>}/>
            <Route path="/meals" exact element={<MealsPage/>}/>
        <Route path="/auth" exact element={()=>{!user? <Auth/>:<Navigate to="/workouts"/>}}/>
        </Routes>
  
        </Container>
        </BrowserRouter>
    );
}

export default App;

我收到一條錯誤消息:

react-dom.development.js:67 
        
       Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

我假設它來自 Auth 路由,因為它沒有指定當我們擁有該特定路由時要呈現的元素,但它指定了一個函數。 基本上,當用戶登錄時,他不應該看到 auth 組件,因為他已經登錄並且他應該被重定向到“/workouts”路徑,這是應用程序中的另一個頁面。

你能幫我解決這個問題嗎?

這里element={()=>{!user? <Auth/>:<Navigate to="/workouts"/>}} element={()=>{!user? <Auth/>:<Navigate to="/workouts"/>}} element={user? <Navigate to="/workouts"/> : <Auth/>} element={user? <Navigate to="/workouts"/> : <Auth/>}或返回像element={()=>!user? <Auth/>:<Navigate to="/workouts"/>} element={()=>!user? <Auth/>:<Navigate to="/workouts"/>}element={()=>{return !user? <Auth/>:<Navigate to="/workouts"/>}} element={()=>{return !user? <Auth/>:<Navigate to="/workouts"/>}}

查看<Route />的文檔element prop 是一個元素,而不是返回元素的函數

因此,您應該能夠簡單地刪除函數調用並直接傳遞元素:

<Route
  path="/auth"
  exact
  element={!user ? <Auth/> : <Navigate to="/workouts"/>}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM