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

React渲染JSON列表时map报错:Cannot read property 'map' of null求助

Fixing "TypeError: Cannot read property 'map' of null" in Your React Component

Ah, I know this issue well! The problem here is timing: when your component first renders, this.state.JsonList is still null (even though later it gets updated to your array of times). The console.log you're seeing is from after the state has been updated, but the initial render already tried to call .map() on null—that's where the error comes from.

Here are a few simple fixes to resolve this:

1. Initialize State with an Empty Array

The cleanest approach is to set your initial state for JsonList to an empty array instead of null. This way, .map() will work on the empty array (it just won't render any items) until your data loads.

If you're using a constructor:

constructor(props) {
  super(props);
  this.state = {
    JsonList: [] // Start with empty array instead of null
  };
}

Or if you're using class fields (modern React):

state = {
  JsonList: []
};

2. Add a Safety Check Before Mapping

If you can't change the initial state, you can add a conditional to make sure JsonList exists before calling .map().

Option A: Optional Chaining (ES2020+)

This is concise and safe:

const items = this.state.JsonList?.map(item => <li>{item.res}</li>);

The ?. operator will only call .map() if JsonList is not null or undefined.

Option B: Ternary Conditional

For older environments that don't support optional chaining:

const items = this.state.JsonList 
  ? this.state.JsonList.map(item => <li>{item.res}</li>) 
  : [];

Option C: Nullish Coalescing

Another modern approach to fall back to an empty array:

const items = (this.state.JsonList ?? []).map(item => <li>{item.res}</li>);

Any of these methods will prevent the error by ensuring you never call .map() on null. The first solution (initializing with an empty array) is usually the best practice because it keeps your render logic clean.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:31:28