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

馋奶兔 提交于 2019-12-12 03:39:36

问题


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:

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.


回答1:


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}



回答2:


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
}


来源:https://stackoverflow.com/questions/43201982/react-redux-can-view-props-in-browser-console-but-return-undefined-when-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!