javascript - 在 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 对象,它的内容也会很好地显示在控制台中。一旦我指定了我想要的字符串,我就会得到一个未定义的错误。
有没有具体的做法?
解决方案
如果您的数组最初是空的,您需要检查它。你可以这样做length
:
if (this.props.postData.length) {
const { post_content } = this.props.postData[0];
return <div>{post_content}</div>;
}
return <div>No data</div>;;
推荐阅读
- python - 为什么我在 Pygame 中绘制后第二张图像没有出现在第一张图像之上
- javascript - 使用合并图像时无法加载图像
- arrays - Apexchart xaxis 标签在 Reactjs 中显示为数字而不是字符串
- android - 按钮未添加到“总”文本视图中
- udp - 如果 UDP 发送方发送了太多接收方无法接收的信息,会发生什么?
- node.js - NodeJs错误检查用户是否使用绑定控制器进行了身份验证
- react-native - 显示多层次的 Json 数据
- c# - 我如何在一个视图中有两个模型类?
- r - 有比例表时如何绘图
- .net - 点网 XML 节点 Un-Escape 双引号