【问题标题】:Can't select array item from react props无法从反应道具中选择数组项
【发布时间】:2017-11-03 12:00:05
【问题描述】:

我在从道具中选择无状态反应组件中的项目时遇到问题。

一般设置很简单:

const useritem = {
  name: 'foo',
  images: [
    {url: 'urlstring1'},
    {url: 'urlstring2'}
  ]
}

const App = () => (
  <div style={styles}>
    <Hello name="CodeSandbox" />
    <h2>Start editing to see some magic happen {'\u2728'}</h2>
    <User useritem={useritem}/>
  </div>
);

const User = (props) => (
  <p>{`imageurl is ${props.useritem.images[0].url}`}</p>
);

render(<App />, document.getElementById('root'));

查看工作示例:https://codesandbox.io/s/9yk98okk64

我有一个带有名称和图像数组的用户对象(硬编码为 const useritem),其中包含两个图像对象。我将对象作为道具传递给用户组件。

让我头疼的部分是: props.useritem.images[0].url
在上面的示例中,它当然可以工作。在我的本地环境中,它显示“无法读取未定义的属性 '0'”。所以图像数组似乎不存在,但是我仍然可以毫无问题地访问 useritem.name 的等价物。

有人知道问题出在哪里吗?正如我所说,上面的示例在代码框中有效(正如我假设的那样)。它会破裂的原因可能是什么?

【问题讨论】:

  • 看着你的 CodeSandBox 狙击手,我看到“imageurl 是 urlstring1”,所以看起来没问题……我担心这没有帮助
  • 是的,这就是重点。它可以正常工作,但不在我的应用程序中。这是一个带有反应前端的流星应用程序。最令人困惑的部分是我可以访问“props.useritem.name”,但是“props.useritem.images[0].url”出现错误 -> 所以我也认为这不是道具没有被传递的问题下来...
  • 为了调试目的,您需要研究两件事。组件如何接收道具(意思是它来自异步请求),其次是你得到的 props.userItem 对象是什么
  • 谢谢@ShubhamKhatri。它来自一个异步请求。

标签: arrays reactjs


【解决方案1】:

我在promise返回嵌套对象时遇到过这种问题。

这可能对你有用:

props.useritem.images ? props.useritem.images[0].url : 'loading...'

这将检查图像属性是否存在,然后获取 URL,否则显示加载文本。

【讨论】:

    猜你喜欢
    • 2019-06-17
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2019-11-29
    • 2021-08-16
    • 2018-04-27
    • 2021-07-21
    相关资源
    最近更新 更多