简体   繁体   中英

React Redux: Can view props in browser console, but return undefined when rendered

I am having a problem rendering the props value in react.

I have added data fetched from an API to a redux store, and then mapped the state to my App component. The data shows up in my props when I view the component using react dev tools, and I can access the value of the API prop through the console by typing:

$r.props.products.items[0].title

Here's an image of Chrome dev tools illustrating ability to access props from App component for reference:

Chrome开发人员工具展示了从App组件访问道具的功能

But when I try to render the props in the App component using

{this.props.products.items[0].title}

The component breaks and I receive an error in the console saying:

Uncaught TypeError: Cannot read property 'title' of undefined

If it helps, I've created a gist here showing my App.js component where the state is mapped to the props, the actions and reducers for the redux store.

If anyone can help me that would be great. I've been pulling my hair out over it all day.

Reason is, you are fetching the data from api, until you didn't get the response {this.props.products.item} will be undefined, because render will get executed before you get the response. So either you need to hold the rendering by using some bool until you didn't get the response or put the check, like this:

{this.props.products.items && this.props.products.items[0].title}

If the previous answer is not working, the only thing I can think of is that items may exist as an empty array, in the form of this.props.products.items = []

Try:

{
  this.props.products.items &&
  this.props.products.items.length > 0 &&
  this.props.products.items[0].title
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM