【问题标题】:TypeError: Cannot read property '0' of undefined when building my react appTypeError:构建我的反应应用程序时无法读取未定义的属性“0”
【发布时间】:2022-01-06 21:50:16
【问题描述】:

在构建我的 React 应用程序以进行部署时,我收到此错误

TypeError:无法读取未定义的属性“0”

当我在 port3000 上进行渲染时,我没有看到这个错误,但只是在构建应用程序时得到它。

谁能帮忙解决这个问题?

import { useState } from "react";
import styles from "./Tabs.module.css"

const Tabs = ({ children}) => {
    const [activeTab, setActiveTab] = useState (children [0].props.label);

    const handleClick =( e, newActiveTab ) => {
        e.preventDefault();
        setActiveTab(newActiveTab);
    }


    return (
        <div>
            <ul className= {styles.tabs}>
                {children.map ((tab) => {
                    const label = tab.props.label;
                    return (
                    <li
                    className= {label == activeTab ? styles.current : ""} 
                    key= {label}
                    >
                      <a href="#" onClick={(e) => handleClick (e, label)}>{label}
                      </a>
                    </li>
                    )
                })}
            </ul>
            {children.map ((tabcontent1) => {
                if (tabcontent1.props.label == activeTab)
                return (
                <div key= {tabcontent1.props.label} className= {styles.content}>{tabcontent1.props.children} 
                </div>
                );
            })}
            
        </div>
       
    );
}

export default  Tabs ;

【问题讨论】:

  • children [0] 尚未定义。 children prop 并不是真正的数组,您应该使用顶级 Children 来映射子组件。你在 Nextjs 中使用 SSR 吗?
  • 您的页面可能正在静态呈现。因此,在构建时 children 未定义。下一个 js 尝试静态渲染它,因此它访问它尝试执行 undefined[0] 的初始状态,这是一个错误。因此,让您的 children 变量可用于静态侧面渲染。
  • @rakesh shrestha。感谢您的贡献。请表达代码以使 children 变量用于静态侧渲染
  • 是的,我使用 SSR,但我认为我没有定义它,请协助

标签: arrays reactjs visual-studio-code next.js react-props


【解决方案1】:

在下一个 js 中,当您不在页面中放置 export const getServerSideProps = () =&gt; {} 时,该页面会自动进行静态侧渲染。在开发模式下,您可能会在右下角看到一个闪电符号。无论如何,您可以在 nextjs 上阅读 data-fetching 上的文档。但是,您可以通过将子项设置为useEffect,轻松解决您在这种情况下的问题。

// handle null on your active tab render function
const [activeTab, setActiveTab] = useState(null);

useEffect(() => {
 if(children.length)
  children[0].props.label
}, [children])

另一个代码示例: *代码结构和您尝试做的方式的简单更改。它正在反应,但在下一个也是一样的 *

import React from "react";

const Tabs = ({ tabsData }) => {
  const [activeTabIndex, setActiveTabIndex] = React.useState(0);

  const switchTabs = (index) => setActiveTabIndex(index);

  return (
    <div style={{ display: "flex", gap: 20, cursor: "pointer" }}>
      {/* Here active tab is given a green color and non actives grey */}
      {tabsData.map((x, i) => (
        <div
          key={i}
          style={{ color: activeTabIndex === i ? "green" : "#bbb" }}
          onClick={() => switchTabs(i)}
        >
          {x.label}
        </div>
      ))}
      {/* Show Active Tab Content */}
      {tabsData[activeTabIndex].content}
    </div>
  );
};

export default function App() {
  // You can place it inside tabs also in this case
  // but lets say you have some states on this component
  const tabsData = React.useMemo(() => {
    return [
      // content can be any component or React Element
      { label: "Profile", content: <p>Verify all Input</p> },
      { label: "Settings", content: <p>Settings Input</p> },
      { label: "Info", content: <p>INput info</p> }
    ];
  }, []);

  return (
    <div className="App">
      <Tabs tabsData={tabsData} />
    </div>
  );
}

这里也是一个示例沙箱https://codesandbox.io/s/serverless-night-ufqr5?file=/src/App.js:0-1219

【讨论】:

  • 当我添加上面的代码行时 - 首先选项卡在我按下它之前是不活动的。它是空白的。在构建时出现错误 - 无法在选项卡处读取未定义的属性“地图”。
  • 你能在代码沙箱上创建一个复制品吗?
  • 感谢您的支持。我现在在代码沙箱上拥有所有选项卡式组件。 codesandbox.io/s/cool-joana-wsib8?file=/src/index.js 。我现在拥有的是 = TypeError: Cannot read property '0' of undefined when building the entire project.
  • 我没有收到你的任何回复@rakeshshrestha,
  • 对不起@GMERT,您只是复制粘贴了整个代码而没有适当的组件。我无法在我的机器上运行它。请提供一个有效的小演示,以便我可以对其进行适当的编辑。你也可以在 react codesandbox 上做到这一点。下次我会更新它。
猜你喜欢
  • 1970-01-01
  • 2020-08-09
  • 2021-04-23
  • 2022-09-27
  • 2020-09-07
  • 2021-06-22
  • 2021-07-10
  • 2017-01-01
  • 2021-01-16
相关资源
最近更新 更多