【问题标题】:Using match() for regex on react app getting error使用 match() 进行正则表达式反应应用程序出错
【发布时间】:2020-03-18 02:45:33
【问题描述】:
componentDidMount(){
  axios.get('/sites/multiscreen/templates').then(res => {
    if(res.data.template_id.match(/^[a-z0-9]+$/i)){
      this.setState({
        templates: res.data,
      });
    }
  })
}

我得到的错误是:

未处理的拒绝(TypeError):无法读取未定义的属性“匹配”

感谢任何帮助!

【问题讨论】:

  • 听起来template_id 不是字符串。
  • 它是 JSON...我如何将 match() 与 json 一起使用?转换成字符串?
  • 你能发布你的res.data吗?错误是说 res.data.template_id 未定义。

标签: javascript regex reactjs match


【解决方案1】:

在调用match 之前,您必须确保res.data 具有价值。我建议你使用这个:

componentDidMount(){
  axios.get('/sites/multiscreen/templates').then(res => {
    if(!!res && 
       !!res.data &&
       !!res.data.template_id &&
       /^[a-z0-9]+$/i.test(res.data.template_id)) 
    {
      this.setState({templates: res.data});
    }
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多