Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.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/22.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 ReactJS状态或逻辑运算符总是导致类型错误_Javascript_Reactjs_Logical Operators - Fatal编程技术网

Javascript ReactJS状态或逻辑运算符总是导致类型错误

Javascript ReactJS状态或逻辑运算符总是导致类型错误,javascript,reactjs,logical-operators,Javascript,Reactjs,Logical Operators,我为仍然抛出错误的组件提供了一个简单的状态设置:TypeError:无法使用以下代码读取未定义的属性“year”: export default class Login extends Component { state = { isLoading: false, events: this.props.events, activeDate: { year: this.props.events[0].year || "", month: this

我为仍然抛出错误的组件提供了一个简单的状态设置:
TypeError:无法使用以下代码读取未定义的属性“year”:

export default class Login extends Component {
  state = {
    isLoading: false,
    events: this.props.events,
    activeDate: {
      year: this.props.events[0].year || "",
      month: this.props.events[0].months[0].month || "",
    }
  };

  //...

}

我很难理解为什么会出错,而不是仅仅将值设置为null<代码>未定义的
应将二进制操作呈现为false,并默认为
“”
。有人能解释一下吗

我没有使用
year:this.props.events[0].year | | |“
,而是发现这同样有效,
year:&&this.props.events[0].year
。AND运算符将等于最后一个真值


但是,正如@AlexanderStaroselsky所指出的,这不是最佳实践。有关更多详细信息,请参见此。

您可以验证数组中位置0处的对象是否为空,然后在访问数组对象的属性之前使用
&&
。最后,添加
|
,当两个条件都为
null
未定义时指定默认值

this.props.events[0]和&this.props.events[0].year

我猜您想用ESnext编写的是
年:这?.props?.events?[0]?.year | |?“”,
(请参阅),但它还没有广泛使用(可以始终使用babel)。问题是,
this.props.events[0]
未定义的
,因此没有名为
year
的属性。在某些时刻,甚至是短暂的时刻,事件是未定义的或为空的。您需要添加默认值或增强逻辑来处理空数组或未定义的数组。这可以用于在父级添加默认值。可以说,从道具派生状态是一种反模式@亚历山大·斯塔洛塞尔斯基谢谢你!这篇文章确实帮助我澄清了一些事情。