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

IT技术 javascript reactjs meteor-react
2021-05-07 03:33:17

我是使用 react.js 的新手,正在尝试编写一个可重用的组件,该组件具有传递给它的可选属性。在组件中,该可选属性使用meteor 从数据库中提取数据,然后我想检查返回的对象上是否存在属性(任务上存在parent_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>
    )
  }
});
4个回答

有问题的props是什么?怎么样

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

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

if ('parent_task' in current_task)

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

您可以使用两个选项。&& 运算符和 If 语句来检查props是否存在。选项 1 将检查该属性是否存在,然后运行代码的第二部分。它就像没有 if 的 if 一样。

选项1

this.props.property && this.props.property

选项 2

if(this.props.property){
this.props.property
}

这也适用于函数名称。

您也可以使用此检查来呈现组件和标签。

这对我有用

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