Check if property exists using React.js

2020-02-26 03:37发布

I'm new to using react.js, and am trying to write a re-usable component that has an optional property passed to it. In the component, that optional property pulls data from a db using meteor, then I want to check if a property exists on the returned object (parent_task exists on task), and if exists, adds a link. This seems fairly simple, but I keep getting errors. Does anyone have any suggestions on what I might be missing? Is there a jsx gotcha that I'm missing?

<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>
    )
  }
});

5条回答
Bombasti
2楼-- · 2020-02-26 04:22

I figured this out. Apparently it was a syntax issue - you need to use a string when searching for properties in objects. The line below works:

if ('parent_task' in current_task)
查看更多
闹够了就滚
3楼-- · 2020-02-26 04:25

You need to return out of getParentTaskLink() with the link you need.

 if (current_task.parent_task) {
      return (<a href="#">link</a>);
    } else { return null; }
查看更多
看我几分像从前
4楼-- · 2020-02-26 04:28

I suggest to try this elegant solution to check callback property on your component:

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

or applying destructuring:

const { onClickCallback } = this.props;
if(typeof onClickCallback === 'function') { 
// Do stuff; 
}
查看更多
唯我独甜
5楼-- · 2020-02-26 04:33

what is the prop in question? how about

{this.props.propInQuestion ? <a href="#">link</a> : null}
查看更多
冷血范
6楼-- · 2020-02-26 04:42

Check if a property exists using React.js

There are two options you can use. the && operator and If statement to check if the props exist. Option 1 will check if the property exists then run the second part of the code. It works like an if without the if.

Option 1

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

Option 2

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

This also works with function names.

You can use this also check to render components and tags.

查看更多
登录 后发表回答