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
意思是:函数作为React子函数是无效的。如果你从render中返回一个Component而不是<Component />,可能会发生这种情况。或者你想要调用这个函数而不是返回它。
产生场景之一:使用 react-router-dom v6 中的 useRoutes API 实现路由集中管理,发生报错
解决: 这个我是一脸蒙蔽,莫名其妙的,于是我就看了文档,发现原来是useRoutes 中 element 属性值我写成 一个方法,但是 他需要一个 元素标签。
错误:
import React, { lazy } from "react";
import {
Link,
useNavigate,
useRoutes,
Outlet,
Navigate,
} from "react-router-dom";
function Home() {
return (
<div>
<p>首页组件Home</p>
</div>
);
}
function About() {
const naviate = useNavigate();
function goAboutdetail() {
naviate("/about/aboutDetail");
}
return (
<div>
<div>关于页面About</div>
<div onClick={goAboutdetail}>点击跳转到到 Aboutdetail 组件 </div>
<Outlet></Outlet>
</div>
);
}
function Aboutdetail() {
return <div>Aboutdetail 子页面</div>;
}
function Detail() {
return <div>About 子页面</div>;
}
const routes = [
{
path: "/",
element: <Navigate to={"/home"} />,
},
{
path: "/home",
element: Home,
},
{
path: "/about",
element: About,
children: [
{
index: true,
// path: "aboutDetail",
element: Aboutdetail,
},
{
path: "detail",
element: Detail,
},
],
},
];
function App() {
return (
<div>
<div className="App">
<Link to="/">首页</Link>
<br />
<Link to="/about">关于</Link>
</div>
{useRoutes(routes)}
</div>
);
}
export default App;
不报错:
import React, { lazy } from "react";
import {
Link,
useNavigate,
useRoutes,
Outlet,
Navigate,
} from "react-router-dom";
function Home() {
return (
<div>
<p>首页组件Home</p>
</div>
);
}
function About() {
const naviate = useNavigate();
function goAboutdetail() {
naviate("/about/aboutDetail");
}
return (
<div>
<div>关于页面About</div>
<div onClick={goAboutdetail}>点击跳转到到 Aboutdetail 组件 </div>
<Outlet></Outlet>
</div>
);
}
function Aboutdetail() {
return <div>Aboutdetail 子页面</div>;
}
function Detail() {
return <div>About 子页面</div>;
}
const routes = [
{
path: "/",
element: <Navigate to={"/home"} />,
},
{
path: "/home",
element: <Home></Home>,
},
{
path: "/about",
element: <About></About>,
children: [
{
index: true,
// path: "aboutDetail",
element: <Aboutdetail></Aboutdetail>,
},
{
path: "detail",
element: <Detail></Detail>,
},
],
},
];
function App() {
return (
<div>
<div className="App">
<Link to="/">首页</Link>
<br />
<Link to="/about">关于</Link>
</div>
{useRoutes(routes)}
</div>
);
}
export default App;