使用React.js检查属性是否存在

49

我刚开始使用react.js,尝试编写一个可重复使用的组件,并向其传递一个可选属性。在组件中,该可选属性使用meteor从数据库中提取数据,然后我想检查返回对象上是否存在一个属性(parent_task存在于task上),如果存在,则添加一个链接。这似乎很简单,但我一直在遇到错误。有人对我可能忽略的内容有什么建议吗?我是否忽略了JSX的陷阱?

<Header task={params.task_id} />  // rendering component with property

// Task List Header
Header = React.createClass({
  mixins: [ReactMeteorData],

  getMeteorData() {
    var handle = Meteor.subscribe('tasks');

    return {
      taskLoading: ! handle.ready(),
      task: Tasks.findOne({_id: this.props.task})
    }
  },

  getParentTaskLink() {
    if (!this.data.taskLoading) {
      var current_task = this.data.task;

      if (parent_task in current_task) {  // or current_task.hasOwnProperty(parent_task)
        console.log("parent_task exists!");
      }
    }
  },

  render() {
    return (
      <div className="bar bar-header bar-calm">
        {this.getParentTaskLink()} // eventually return anchor element here
        <h1 className="title">Hello World</h1>
      </div>
    )
  }
});

你在哪里遇到问题?是在getParentTaskLink函数中吗? - Dominic
不是这样的,为什么在data.taskLoading为false的检查中data.task会为空呢?如果是这样,为什么不直接写成if (!this.data.taskLoading && this.data.task) {,这样你就知道可以在里面使用它了。 - Dominic
Props 是一个 JS 对象,因此您可以使用 JS 函数来检查对象是否包含...请参阅 https://dmitripavlutin.com/check-if-object-has-property-javascript/。 - Hyzyr
9个回答

51

所讨论的道具是什么?它怎么样?

{this.props.propInQuestion ? <a href="#">link</a> : null}

我想查看数据对象(task)返回的属性parent_task是否存在。我编辑了问题以使其更清晰。我尝试了您的建议,但它仍然给我一个错误。 - bgmaster
8
写成{this.props.propInQuestion && <a href="#">link</a>}不是更容易吗? - Jay Wick
1
要么这样,要么那样。有些开发人员会被 && 保护条件搞糊涂。我可以两种方式都行。 - meta-meta
4
使用{this.props.propInQuestion && <a href="#">链接</a>}时,请确保this.props.propInQuestion是布尔值或将其强制转换为布尔值。如果this.props.propInQuestion是0,它会呈现0。 - meta-meta
如果this.props.propInQuestion是一个现有的参数并且是布尔值,那么当它带有“false”值时,你会被诱导出错。我使用了this.props.propInQuestion != null,并获得了所期望的结果。@meta-meta,我不确定您想表达同样的意思。 - Victor
@Victor,出了什么错误?如果this.props.propInQuestion === false{this.props.propInQuestion && <a href="#">link</a>}将会被计算为false。React不会渲染这个。 - meta-meta

15

我弄清楚了。显然这是一个语法问题 - 在搜索对象属性时需要使用字符串。下面的代码行有效:

if ('parent_task' in current_task)

10

对我有效的方法:

if ('myProperty' in this.props) {}

或者
if (this.props.myProperty !== undefined) {}


if (this.props.hasOwnProperty('myProperty')) {}

下一个条件不适用于数字属性,因为0值将无法起作用(例如对于空字符串):
if (this.props.MaxValue) {}

在我看来,这个答案比被采纳的更好。一个属性可能存在但其值为false(或“falsy”),在这种情况下,如果你使用三元运算符进行检查,结果将是错误的,如果你想要询问的是,如标题所示,该属性是否存在。 - RdC1965

4

这对我有效

if(this.props.test === undefined){
    console.log('props.test is not defined')
}

4

使用React.js检查属性是否存在

您可以使用两个选项。使用“&&”运算符和If语句来检查props是否存在。选项1将检查属性是否存在,然后运行代码的第二部分。它的工作方式类似于if但没有if。

选项1:


```javascript {props.property && ( //code to run if property exists )} ```
this.props.property && this.props.property

选项 2
if(this.props.property){
this.props.property
}

这个方法同样适用于函数名称。

你也可以使用它来检查渲染组件和标签。


请详细阐述您的答案,以帮助其他人解决这个问题。 - lprakashv
如果您期望的值是布尔值,那么如果它带有“false”值,它将无法按预期工作。 - Victor

0
if(props.hasOwnProperty('propertyName')){
  //do something
} else {
  //do something else
}

0

我建议尝试这种优雅的解决方案来检查您组件上的回调属性:

if(typeof this.props.onClickCallback === 'function') { 
// Do stuff; 
}

或者应用解构:

const { onClickCallback } = this.props;
if(typeof onClickCallback === 'function') { 
// Do stuff; 
}

-1

最受欢迎的答案

props.propInQuestion ? 'a' : 'b'

如果 prop 是布尔值并且您尝试检查其是否存在,则不起作用。

根据 如何在 JavaScript 中检查对象是否具有键? 的说法,最快的方法是使用 props.hasOwnProperty('propInQuestion'),但要注意这不会搜索原型链。


-2

你需要从getParentTaskLink()中返回所需的链接。

 if (current_task.parent_task) {
      return (<a href="#">link</a>);
    } else { return null; }

抱歉,我只是为了调试而在那里留下了console.log。错误显示parent_task未定义。 - bgmaster
你尝试过检查 if(current_task[parent_task]) 吗?这应该会给你当前任务中 parent_task 属性的值。 - Bruce
似乎这会给我相同的错误。我知道在某些情况下它不会被定义,这就是为什么我想要检查的原因。我以前在其他应用程序中使用JavaScript从未遇到过这个问题,这让我觉得这是JSX的事情。 - bgmaster
它说parent_task未定义(因为它确实未定义),但这就是我想要检查的原因。 - bgmaster
抱歉,你是对的。我应该输入的是 if(current_task.parent_task)。使用[parent_task]会让它认为parent_task是一个变量而不是属性。我已经编辑了我的原始回答以反映这一点。 - Bruce
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接