Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

javascript - Getting Error: property of 'undefined' in Nested React Router

I am trying to get data through nested react-router but getting the value undefined.

My data:

const data = [
    {
        id: 0,
        name: "Skateboard1",
        price: 20.10,
        img: picture1
    },
    {
        id: 1,
        name: "Skateboard2",
        price: 80.50,
        img: picture2
    }
]

App.js:

const App = () => {
  return (
    <Router>
      <Switch>
 
        <Route exact path="/shop/:id" render={(itemProp) => <ShopItem shopItemId={itemProp.match.params.id} />} />

      </Switch> 
    </Router>
    
  );
}

ShopItem Component:

const ShopItem = (shopItemId) => {

        const item = data.find((i) => i.id === shopItemId) 
    
    return(
        <div>
               <h2>{item.name}</h2>
        </div>
    )
}

Error:

TypeError: Cannot read property 'name' of undefined

on console.log(shopItemId)

{
  shopItemId: "1"
}

It seems like a silly mistake. But can't get what's wrong.

Please any help would be appreciated

question from:https://stackoverflow.com/questions/65947487/getting-error-property-of-undefined-in-nested-react-router

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The function data.find((i) => i.id === shopItemId) didn't find any element that matches the comparison, so item is undefined. shopItemId is an object, so the real value is shopItemId.shopItemId and use == operator since one value is an integer and the other is a string like:

const item = data.find((i) => i.id == shopItemId.shopItemId)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...