首页 > 解决方案 > 在 React 中将数据分配给变量

问题描述

我第一次使用 React 和来自数据库的实际实时数据。我正在使用本文中概述的 fetch 并且效果很好。我已经能够从 php 文件中获取数据以打印到 react 中。

我现在遇到了麻烦,因为 React 有点停止了意义。有些变量可以正常工作,而其他使用完全相同数据的变量则不行。

例如:给定这个对象数组 在此处输入图像描述

我可以这样做将它分配给一个变量:

var posts = this.props.postData.map(function(entry, index){
            return <li>{entry.post_title}</li>;
          })

它会很好地输出:

在此处输入图像描述

但是,在与上述相同的函数中,如果我想将特定字符串从对象分配给变量,突然反应会告诉我对象未定义。

var singlepost = <span>{this.props.postData[0].post_content}</span>

var singlepost = this.props.postData[0].post_content;

乃至:

var singlepost = this.props.postData[0];
return (
    <div>{singlepost.post_content}</div>
)

将导致: 在此处输入图像描述

无论我尝试什么,React 一直告诉我它是未定义的,即使我在使用它之前 console.log 对象,它的内容也会很好地显示在控制台中。一旦我指定了我想要的字符串,我就会得到一个未定义的错误。

有没有具体的做法?

标签: javascriptreactjs

解决方案


如果您的数组最初是空的,您需要检查它。你可以这样做length

if (this.props.postData.length) {
  const { post_content } = this.props.postData[0];
  return <div>{post_content}</div>;
}
return <div>No data</div>;;

推荐阅读