Uncaught Typeerror: Cannot Read Property 'hasclass' of Undefined
Got an mistake like this in your React component?
Cannot read belongings `map` of undefined
In this mail we'll talk most how to set this one specifically, and along the way you'll learn how to approach fixing errors in full general.
We'll cover how to read a stack trace, how to translate the text of the mistake, and ultimately how to fix it.
The Quick Fix
This error usually ways you're trying to utilize .map
on an array, but that assortment isn't divers yet.
That's often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the state properly. That means if it will eventually be an array, use useState([])
instead of something like useState()
or useState(zilch)
.
Let'south look at how we can interpret an fault message and rails down where it happened and why.
How to Find the Error
First gild of concern is to figure out where the fault is.
If y'all're using Create React App, it probably threw upward a screen like this:
TypeError
Cannot read belongings 'map' of undefined
App
6 | render (
7 | < div className = "App" >
8 | < h1 > Listing of Items < / h1 >
> ix | {items . map((item) => (
| ^
10 | < div primal = {item . id} >
11 | {particular . proper name}
12 | < / div >
Await for the file and the line number beginning.
Here, that's /src/App.js and line 9, taken from the light gray text above the lawmaking cake.
btw, when you see something like /src/App.js:9:thirteen
, the way to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If yous're looking at the browser console instead, you lot'll need to read the stack trace to effigy out where the fault was.
These ever look long and intimidating, but the trick is that unremarkably you tin can ignore most of it!
The lines are in order of execution, with the most recent first.
Here's the stack trace for this error, with the only important lines highlighted:
TypeError: Cannot read property 'map' of undefined at App (App.js:nine) at renderWithHooks (react-dom.development.js:10021) at mountIndeterminateComponent (react-dom.development.js:12143) at beginWork (react-dom.evolution.js:12942) at HTMLUnknownElement.callCallback (react-dom.development.js:2746) at Object.invokeGuardedCallbackDev (react-dom.development.js:2770) at invokeGuardedCallback (react-dom.development.js:2804) at beginWork $one (react-dom.development.js:16114) at performUnitOfWork (react-dom.evolution.js:15339) at workLoopSync (react-dom.evolution.js:15293) at renderRootSync (react-dom.evolution.js:15268) at performSyncWorkOnRoot (react-dom.evolution.js:15008) at scheduleUpdateOnFiber (react-dom.development.js:14770) at updateContainer (react-dom.evolution.js:17211) at eval (react-dom.evolution.js:17610) at unbatchedUpdates (react-dom.development.js:15104) at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609) at Object.render (react-dom.development.js:17672) at evaluate (index.js:seven) at z (eval.js:42) at 1000.evaluate (transpiled-module.js:692) at exist.evaluateTranspiledModule (manager.js:286) at be.evaluateModule (director.js:257) at compile.ts:717 at l (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.e. < computed > [every bit next] (runtime.js:97) at t (asyncToGenerator.js:three) at i (asyncToGenerator.js:25)
I wasn't kidding when I said you could ignore nearly of it! The offset 2 lines are all we care virtually here.
The get-go line is the error message, and every line later on that spells out the unwound stack of function calls that led to it.
Let's decode a couple of these lines:
Here nosotros have:
-
App
is the name of our component function -
App.js
is the file where information technology appears -
9
is the line of that file where the fault occurred
Allow'south look at another one:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the proper name of the function where this happened -
react-dom.development.js
is the file -
15008
is the line number (it's a big file!)
Ignore Files That Aren't Yours
I already mentioned this only I wanted to land it explictly: when you're looking at a stack trace, you can almost always ignore any lines that refer to files that are outside your codebase, similar ones from a library.
Usually, that means you'll pay attention to only the showtime few lines.
Scan down the list until information technology starts to veer into file names you don't recognize.
In that location are some cases where you practice care most the full stack, but they're few and far between, in my experience. Things like… if you suspect a problems in the library you lot're using, or if yous recollect some erroneous input is making its fashion into library code and bravado up.
The vast bulk of the time, though, the bug will exist in your own lawmaking ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told u.s. where to wait: line 9 of App.js. Let's open that upwardly.
Here's the full text of that file:
import "./styles.css" ; export default function App () { permit items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( detail => ( < div key = { item .id } > { item .proper noun } </ div > )) } </ div > ) ; }
Line 9 is this one:
And just for reference, here's that mistake message once again:
TypeError: Cannot read property 'map' of undefined
Let's break this down!
-
TypeError
is the kind of error
In that location are a handful of born mistake types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful part of the error message)
-
Cannot read property
means the code was trying to read a property.
This is a proficient inkling! There are just a few ways to read properties in JavaScript.
The most common is probably the .
operator.
As in user.name
, to access the name
belongings of the user
object.
Or items.map
, to admission the map
property of the items
object.
There's as well brackets (aka foursquare brackets, []
) for accessing items in an array, like items[v]
or items['map']
.
You might wonder why the fault isn't more than specific, like "Cannot read function `map` of undefined" – simply call up, the JS interpreter has no idea what nosotros meant that type to exist. It doesn't know information technology was supposed to be an assortment, or that map
is a function. It didn't get that far, because items
is undefined.
-
'map'
is the holding the code was trying to read
This 1 is another great clue. Combined with the previous fleck, you tin be pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a inkling well-nigh the value of the variable
It would exist way more useful if the error could say "Cannot read property `map` of items". Sadly information technology doesn't say that. It tells you the value of that variable instead.
And then at present yous tin piece this all together:
- detect the line that the error occurred on (line 9, here)
- scan that line looking for
.map
- expect at the variable/expression/whatever immediately before the
.map
and be very suspicious of information technology.
Once you lot know which variable to look at, you can read through the function looking for where it comes from, and whether it's initialized.
In our little example, the merely other occurrence of items
is line 4:
This defines the variable merely information technology doesn't set information technology to annihilation, which means its value is undefined
. There'south the problem. Gear up that, and you ready the error!
Fixing This in the Existent World
Of form this example is tiny and contrived, with a unproblematic mistake, and it's colocated very close to the site of the error. These ones are the easiest to set up!
At that place are a ton of potential causes for an error like this, though.
Maybe items
is a prop passed in from the parent component – and y'all forgot to pass it down.
Or maybe you did laissez passer that prop, just the value being passed in is actually undefined or nil.
If it's a local land variable, maybe you lot're initializing the state as undefined – useState()
, written like that with no arguments, volition do exactly this!
If it's a prop coming from Redux, mayhap your mapStateToProps
is missing the value, or has a typo.
Any the case, though, the procedure is the aforementioned: offset where the fault is and work backwards, verifying your assumptions at each point the variable is used. Throw in some panel.log
s or utilize the debugger to inspect the intermediate values and figure out why it's undefined.
You'll get it fixed! Good luck :)
Success! At present check your email.
Learning React tin be a struggle — so many libraries and tools!
My communication? Ignore all of them :)
For a step-past-pace approach, check out my Pure React workshop.
Learn to think in React
- 90+ screencast lessons
- Total transcripts and closed captions
- All the code from the lessons
- Developer interviews
Starting time learning Pure React now
Dave Ceddia'south Pure React is a work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all front end end devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
Belum ada Komentar untuk "Uncaught Typeerror: Cannot Read Property 'hasclass' of Undefined"
Posting Komentar