Lus*_*ust 19 javascript typeerror typescript reactjs
我正在尝试从对象渲染组件,但代码失败并出现错误:
const Login = () => <>login</>
const publicRoutes = [
{
path: '/login',
component: Login
}
]
function AppRouter() {
return <Routes>
{publicRoutes.map(({path, component}) => (
<Route path={path} component={component} /> // warning
))}
</Routes>
)
}
Run Code Online (Sandbox Code Playgroud)
小智 27
从版本 6 开始,React Router Dom 不再采用组件,而是采用元素。[react-router-dom]
因此,您不需要传递组件,而是需要<Component/>像这样传递:
{publicRoutes.map(({path, component: Component}) => (
<Route path={path} element={<Component/>} /> // no warning
))}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用 TS 并在 2023/2024 年遇到此类错误,请记住它可能与 tsconfig 有关!
就我而言,我为两个不同的项目提供了它,解决方案如下所示:
"compilerOptions": {
"paths": {
"react": ["node_modules/@types/react"]
}
}
Run Code Online (Sandbox Code Playgroud)
或者
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["node"],
"emitDecoratorMetadata": true,
"target": "es2021"
},
Run Code Online (Sandbox Code Playgroud)
尝试使用tsconfig.json选项,我希望这对您有帮助,因为在出现该错误之前我花了很多时间,这没有任何意义,导致这篇文章帮助我找到问题的根源