【问题标题】:TypeError: Cannot read property 'map' of undefined in react router when rendering componentsTypeError:渲染组件时无法读取反应路由器中未定义的属性“映射”
【发布时间】:2020-07-31 06:27:40
【问题描述】:

我正在尝试将我的路由文件与我的 App.js 分开以进行代码拆分和更简洁的代码(我认为)。

//routes.js
  

  const routes = [
        {
            path: '/',
            component: () => import('../components/Home')
        },
        {
            path: '/about',
            component: () => import('../components/About')
        }
    ]

    export default routes;

//App.js
import React, {
  Component
} from 'react';

import './App.css';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";
import routes from './router/routes';

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <ul>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/">Home</Link>
            </li>
          </ul>

          <Switch>
            {routes.map((entry) => { return (<Route {...entry} />) })}
          </Switch>
        </div>
      </Router>
    )
  }
}
export default App;

但它给了我一个错误

× TypeError:无法读取未定义的属性“地图”

我正在尝试从路由渲染组件,但它不会渲染,虽然我没有从 vscode 收到任何错误,但在我的浏览器中它给了我错误。

更新: 我将代码从

 {routes.data.map((entry) => { return (<Route {...entry} />) })}
    to 
{routes.map((entry) => { return (<Route {...entry} />) })}

得到新的错误

> Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    in component (created by Context.Consumer)
    in Route (at App.js:30)
    in Switch (at App.js:29)
    in div (at App.js:19)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:18)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)

【问题讨论】:

  • 你能试试吗:{routes.map((entry) => { return () })}

标签: javascript reactjs react-router


【解决方案1】:

您正在尝试在“data”上使用.map,这在您的routes 常量上不存在。使用routes.map

【讨论】:

    【解决方案2】:

    你调用routes.data,所以你的对象应该是这样的:

          const routes = [
           data:[
               {
                   path: '/',
                   component: () => import("./pages/roles/SystemRolesPage")
               },
    
           ]
        ]
    

    与另一个嵌套级别 - U 使用时
    {routes.map((entry) =&gt; { return (&lt;Route {...entry} /&gt;) })}

    它应该可以工作

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多