将数据分配给React中的变量

问题描述 投票:-3回答:4

我是第一次使用React和来自数据库的实际实时数据。我正在使用this article中概述的fetch,而且工作正常。我已经能够从php文件中获取数据以进行反应打印。

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

例如:给定这个对象数组enter image description here

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

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

并且输出就好了:

enter image description here

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

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>
)

将导致:enter image description here

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

有没有具体的这样做?

javascript reactjs
4个回答
0
投票

如果您的阵列最初为空,则需要检查该数组。你可以用length做到这一点:

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

0
投票

你可以做这样的事情

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

0
投票

也许第一次渲染中的postData是空数组。只需添加条件即可渲染:

if(!this.props.postData.length) {
    return null;
}

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

我更喜欢这样做,因为首先让无效的情况让代码更干净。


0
投票

您也可以通过这种方式更好地进行空检查。它有点冗长,但我很欣赏它的安全性。这也有点重复

if (this.props.postData && this.props.postData.length > 0) {
  // Do your computation here
}

如果这符合您的需求,请告诉我们!

© www.soinside.com 2019 - 2024. All rights reserved.