You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactFullpage渲染数据时遇TypeError: Cannot read property '0' of null报错求助

解决ReactFullpage渲染时的TypeError: Cannot read property '0' of null问题

Hey there, let's work through this error together! That TypeError: Cannot read property '0' of null you're hitting is almost certainly because your this.state.items is null at some point during rendering, but your current code only checks if it's undefined. ReactFullpage might be trying to access the first element of your items array before your data finishes loading, and since null isn't caught by your existing check, it throws that error.

Here are a couple of straightforward fixes:

1. Safely check for null/undefined before mapping

You can either use the optional chaining operator (clean and modern) or a short-circuit check to make sure you only call map when items exists:

Option A: Optional Chaining (ES2020+)

<div className="left">
  <ReactFullpage
    licenseKey='xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx'
    sectionsColor={["#000000"]}
    render={({ state, fullpageApi }) => {
      return (
        <div id="fullpage-wrapper">
          {/* Safely call map only if items exists */}
          {this.state.items?.map((img,i) => (
            <img className="section" key={i} src={img.image}></img>
          ))}
        </div>
      );
    }}
  />
</div>

Option B: Short-Circuit Check (compatible with older JS environments)

<div className="left">
  <ReactFullpage
    licenseKey='xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx'
    sectionsColor={["#000000"]}
    render={({ state, fullpageApi }) => {
      return (
        <div id="fullpage-wrapper">
          {/* Only run map if items is truthy (not null/undefined) */}
          {this.state.items && this.state.items.map((img,i) => (
            <img className="section" key={i} src={img.image}></img>
          ))}
        </div>
      );
    }}
  />
</div>

2. Initialize state as an empty array

Another solid approach is to set your items state to an empty array from the start, so it never becomes null or undefined in the first place:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [] // Initialize as empty array instead of null/undefined
    };
  }

  // ... rest of your component logic (data fetching, etc.)
}

This way, even before your data loads, map will just iterate over an empty array and return nothing—no errors thrown.

内容的提问来源于stack exchange,提问作者Pablopg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:07:59