React渲染JSON列表时map报错:Cannot read property 'map' of null求助
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

