Javascript 未捕获类型错误:无法读取属性';名称';空值。仅返回真值
指的是urlJavascript 未捕获类型错误:无法读取属性';名称';空值。仅返回真值,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,指的是urlhttps://app.com/api/v1/${id}。根据id,API返回响应->null或{name:'a'}。对象具有“name”属性。“name”属性要设置状态: this.setState ({ load: this.props.active ['name'] }); 当我单击具有name属性的项目时,它们将显示在控制台中。当我转到一个返回“null”而不带“name”属性的元素时。我有错误:未捕获类型错误:无法读取null的属性“name” class Det
https://app.com/api/v1/${id}
。根据id
,API
返回响应->null
或{name:'a'}
。对象具有“name”属性。“name”属性要设置状态:
this.setState ({
load: this.props.active ['name']
});
当我单击具有name
属性的项目时,它们将显示在控制台中。当我转到一个返回“null”而不带“name”属性的元素时。我有错误:未捕获类型错误:无法读取null的属性“name”
class Details extends Component {
constructor() {
super();
this.state = {
load: null
}
}
componentDidUpdate(prevProps, prevState) {
if(prevProps.active !== this.props.active) {
this.setState({
load: this.props.active['name']
});
}
}
render () {
return (
<div >
</div>
)
}
您可以将其作为另一个条件添加到if语句中
if(prevProps.active !== this.props.active && this.props.active !== null) {
在您的用例中,您可以在组件中检查是否存在
this.props.active
,因此在渲染
中
if (this.props.active) {
return (
<div>Your cool detail view with name attribute.</div>
);
} else {
return (
<div>Your empty detail view.</div>
);
}
if(this.props.active){
返回(
具有名称属性的酷细节视图。
);
}否则{
返回(
您的空细节视图。
);
}
但是,如果这些局部视图是某种列表或集合视图的一部分,则可能需要跳过渲染组件以获得空值。在这种情况下,在上游组件中,应该过滤对象数组(),然后使用过滤后的数组呈现集合
if (this.props.active) {
return (
<div>Your cool detail view with name attribute.</div>
);
} else {
return (
<div>Your empty detail view.</div>
);
}