Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获类型错误:无法读取属性';名称';空值。仅返回真值_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript 未捕获类型错误:无法读取属性';名称';空值。仅返回真值

Javascript 未捕获类型错误:无法读取属性';名称';空值。仅返回真值,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

指的是url
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>
  );
}