检查状态变量是否包含子字符串

Check whether a state variable includes a substring

this.state.foo.includes('bar') returns: TypeError: Cannot read property 'includes' of undefined

只是好奇。我要尝试检查状态变量中的子字符串是否存在。假设我的状态是这样的:

this.state = {
    something: 'foo bar'
}

现在在 return() 函数中我想检查 this.state.something 是否包含子字符串 'foo'.

我知道我可以使用: this.state.something === 'foo bar' ?做这个:做那个

但是由于状态变量的内容是由外部 JSON 文件设置的,我事先并不知道字符串的确切内容,而且在我的代码中的这个特定位置,我只对是否 'foo' 作为子串出现。

如果我尝试:

this.state.something.includes('foo') ? dothis : dothat

我得到一个:TypeError: Cannot read property 'includes' of undefined

indexOf()match() 也会产生错误。

我能做什么? 提前致谢。

为了使用 includes,必须在字符串实例上调用它。因此,例如,如果 this.state.something 的值为 undefined,您将收到此错误。

您可以将值初始化为字符串,或者先使用简单的存在性检查,例如 this.state.something && this.state.something.includes(‘foo’)。在任何一种情况下,如果值不是字符串,您仍然会收到错误消息,因此您也可以考虑进行类型检查。

this.state.something 可能在使用时未定义。 您可以在构造函数中将其默认值设置为空字符串,或者在使用

之前检查是否先定义了 this.state.something
constructor() {
   this.state = {
     something: ''
   }
}

this.state.something && this.state.something.includes('foo');