React报错:Uncaught TypeError: Cannot read property 'map' of undefined求解决
Hey there! Let's break down why you're hitting that Uncaught TypeError: Cannot read property 'map' of undefined error—it's a super common gotcha when starting out with React, so don't worry too much about it.
What's Going On?
The error tells us that this.props.work is undefined when your component tries to call .map() on it. Webpack doesn't catch this because it only checks for syntax errors during compilation, not runtime issues like missing props. Your instructor's code works because they're definitely passing a work prop (an array) to the ExampleWork component when using it—you're either not passing it at all, or it's loading asynchronously and isn't ready when the component first renders.
Fixes to Try
Let's walk through a few solutions to get this working:
Make sure you're passing the
workprop from the parent component
Double-check where you're using<ExampleWork>in your app. It should look something like this:// In your parent component <ExampleWork work={yourWorkArrayData} />If you're not passing the
workprop here,this.props.workwill beundefinedby default.Add default props to
ExampleWork
Even if you forget to pass the prop later, setting a default empty array will prevent the error:ExampleWork.defaultProps = { work: [] };Add a guard clause for async data
Ifworkis coming from an API call or async state, it might beundefinedon the first render. You can add a quick check before mapping:{this.props.work ? ( this.props.work.map((example, idx) => ( <ExampleWorkBubble example={example} key={idx} /> )) ) : ( <p>Loading work examples...</p> )}Or use the optional chain operator (cleaner if your environment supports ES2020+):
{this.props.work?.map((example, idx) => ( <ExampleWorkBubble example={example} key={idx} /> ))}
Updated Code Example
Here's your code with the default props and optional chain added:
import React from 'react'; class ExampleWork extends React.Component { render() { return ( <section className="section section--alignCentered section--description"> {this.props.work?.map((example, idx) => { return ( <ExampleWorkBubble example={example} key={idx} /> ); })} </section> ); } } // Set default prop to avoid undefined errors ExampleWork.defaultProps = { work: [] }; class ExampleWorkBubble extends React.Component { render() { let example = this.props.example; return ( <div className="section__exampleWrapper"> <div className="section__example"> <img alt={example.image.desc} className="section__exampleImage" src={example.image.src} /> <dl className="color--cloud"> <dt className="section__exampleTitle section__text--centered"> {example.title} </dt> <dd></dd> </dl> </div> </div> ); } } export default ExampleWork;
Remember: Webpack won't catch runtime issues like missing props because it only validates your code's syntax, not whether values exist when the app runs in the browser.
内容的提问来源于stack exchange,提问作者CallumD

