React Redux:可以在浏览器控制台中查看道具,但在渲染时返回 undefined [英] React Redux: Can view props in browser console, but return undefined when rendered

查看:45
本文介绍了React Redux:可以在浏览器控制台中查看道具,但在渲染时返回 undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 react 中渲染 props 值时遇到问题.

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

我已将从 API 获取的数据添加到 redux 存储,然后将状态映射到我的 App 组件.当我使用 react dev 工具查看组件时,数据会显示在我的 props 中,我可以通过输入以下内容通过控制台访问 API prop 的值:

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

以下是 Chrome 开发工具的图片,说明了从 App 组件访问 props 的能力,以供参考:

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

但是当我尝试使用

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

组件损坏,我在控制台中收到错误消息说:

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

未捕获的类型错误:无法读取未定义的属性 'title'

Uncaught TypeError: Cannot read property 'title' of undefined

如果有帮助,我已经创建了一个要点 此处 显示我的 App.js 组件状态映射到属性、操作和还原器的还原器.

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.

推荐答案

原因是,你从 api 获取数据,直到你没有得到响应 {this.props.products.item} 将是未定义的,因为 render 将在您获得响应之前执行.所以要么你需要使用一些 bool 来保持渲染,直到你没有得到响应或检查,就像这样:

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}

这篇关于React Redux:可以在浏览器控制台中查看道具,但在渲染时返回 undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆