【问题标题】:Right-hand side of 'instanceof' is not callable'instanceof' 的右侧不可调用
【发布时间】:2017-01-18 00:51:00
【问题描述】:

我正在关注this tutorial 以“检测”数组对象中是否存在唯一数字。这个数字是一个字符串。

我习惯于在 Ruby on Rails 中使用 detect,所以我在 React (JavaScript) 中寻找等价物:

ES6:

...


// this will be "data" in "this.props.data"
data = [
 {
   id: 1,
   order_id: "44",
   name: "Some order number name",
  },
  {
    id: 2,
    order_id: "65",
    ...,
  }
]

  // let num = "44"; Just for this example

  renderCreditNote(num){
    if (num instanceof this.props.data) {
      return num.map(function(p){
        return p.order_id
      });
    }
  }

  render(){
   return({this.renderCreditNote().bind(this)})
  }

...

实际上,这看起来像这样:this.renderCreditNote(this.state.num).bind(this)

因此,如果此 num 在数组中,则仅显示该数组。我这样做对吗?错误是:

未捕获的类型错误:'instanceof' 的右侧不可调用

【问题讨论】:

  • 看起来你需要array.includes,而不是instanceof
  • array.includes 如何处理数组/对象?我知道如果你有一个整数列表它可以工作,但它是否处理检查嵌套对象?
  • Sylar,如果我理解正确,this.props.data 是一个什么数组?你想 1. 检查num 是否在该数组中,如果它返回它的order_id
  • 我在移动设备上。我会在一小时内更新问题
  • 好的,我已经进行了编辑以显示我所拥有的。因此,如果订单 id 为 44,则仅返回该数组。

标签: javascript arrays reactjs


【解决方案1】:

我不了解 Ruby,但根据 detect 的描述,您似乎正在 JavaScript 中寻找 array.find.find 遍历数组 - 如果找到您要查找的项目,则返回并停止迭代,如果未找到任何内容,则返回 undefined

例如:

  renderCreditNote(num){
    return this.props.data.find(function(p){
      return num === p.order_id;
    });
  }

这是一个小提琴:https://jsfiddle.net/7ykt9ze3/

一些 ES6 美化:

  renderCreditNote(num){
    return this.props.data.find(p => num === p.order_id);
  }

请注意,这在稍旧的浏览器中并不完全支持,我从经验中知道 IE11 没有它。但是,它绝对值得 polyfill。

关于您链接的博客 - 在不涉及原型继承的情况下,instanceof 如果输入是数据结构,则基本上返回 true/false。在您链接的博客中,他们正在检测输入是对象还是数组 - 但只有这样他们才能根据该输入采取不同的行动。因此,如果它是一个对象,他们只需返回该对象上的字段,如果它是一个数组,他们会使用 .map 遍历该数组并返回该数组中这些对象的所有名称。

编辑检查渲染方法:

  render(){

   return(<div>{JSON.stringify(this.renderCreditNote().bind(this))}</div>)
  }

【讨论】:

  • 我明白了。我会试试这个并报告。
  • 我现在收到ncaught Invariant Violation: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check render menthod
  • 这是一个反应错误 - 渲染方法需要一个 JSX/html 元素,但您返回的是一个原始 javascript 对象。试试我在编辑中链接的内容,看看是否有任何显示。
  • 你现在失去了我 - 你只有一个数组,data
  • 是的,有很多对象。好的,如果匹配,删除所有其他对象并在数组中保留一个对象,以便我可以迭代。说得通?如果没有,我将只对服务器执行 ajax 并获取所需的数组
【解决方案2】:

您应该将一个函数传递给右侧的实例。试试看this.props.data.constructor

【讨论】:

  • 这消除了错误,但我没有得到“44”的订单ID。
  • 添加 else 语句以返回“44”。你的问题没有说明这一点。
  • 好的,我稍后再回复。谢谢
猜你喜欢
  • 2017-09-16
  • 2019-09-17
  • 2018-01-11
  • 2017-08-28
  • 2020-04-05
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多