[英]Why am I getting error 'Cannot read property 'name' of null' when using a parsed string?
Here I have a react container that holds an object in a variable called strLoc: 在这里,我有一个React容器,该容器将对象保存在名为strLoc的变量中:
(what var strLoc looks like console logged) (var strLoc看起来像控制台记录的一样)
Object {name: "Burj Khalifa", locationLat: "25.197787", locationLong: "55.274862"} 对象{名称:“哈利法塔”,位置纬度:“ 25.197787”,位置长度:“ 55.274862”}
I want to use the name property of the object, but when I try to get {strLoc.name}, I get an error message: 我想使用对象的名称属性,但是当我尝试获取{strLoc.name}时,出现错误消息:
Uncaught TypeError: Cannot read property 'name' of null 未捕获的TypeError:无法读取null的属性“名称”
I don't understand why I can't just pull off the property values to use them? 我不明白为什么我不能仅仅提取属性值来使用它们? Does the problem have something to do with that the object was a string before (I parsed the string and saved the resulting object in var strLoc) ? 问题是否与对象之前是字符串有关(我解析了字符串并将结果对象保存在var strLoc中)?
here is my code: 这是我的代码:
class NoteOutput extends React.Component {
render() {
var strLoc = JSON.parse(this.props.location);
return(
<div>
<div>hello</div>
<div>{strLoc.name}</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
location: state.selectedLocation
};
}
its probably because you have the parse in your render() and it tries to show .name of a string/before it gets parsed. 这可能是因为您的render()中有解析器,并且它试图在解析之前显示字符串的.name。
try this: 尝试这个:
{strLoc && <div>{strLoc.name}</div>}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.