简体   繁体   中英

How to only show map of items if they exist

I am trying to repeat over an object to show some stuff on my app with react, this works fine if I have items in the object already, but at first (before I call the server) the object is empty and thus undefined so it breaks the component. I'm wondering what the best way to work with this is. I am using immutable.js and redux behind my react. I tried something like this in the render of the component:

   render: function(){
    var filterRepeat;
    if (this.props.filters){
        filterRepeat =  { this.props.filters.map(function(filterGroup){
                if (filterGroup.filters.length > 0){
                    return <myFilterCOmponent filterGroup={filterGroup} />
                }
            })
            };
    }

And then I just drop in {filterRepeat} , however it does not seem to like this syntax. I know you can do it like that for normal html but it seems like it's different for the maps evaluate.

I also tried setting it by default in the reducer to see if I could just have a default value set in there with immutable like this :

import { Map } from 'immutable';

var presetState = Map();
presetState.set('filters', {});

export default function reducers(state = presetState, action) {

This does not seem to work either. So I am wondering with that best approach is for something like this with react?

Easy. Just set default props so that it always exists:

var MyComponent = React.createClass({
  getDefaultProps: function() {
    return {
      filters: []
    };
  }
  render: function() {
    var filterRepeat = this.props.filters.map(function(filterGroup, i){
      return (
        <MyFilterComponent key={i} filterGroup={filterGroup} />
      );
    });

    <div>{filterRepeat}</div>
  }
});

I also added a key prop to each MyFilterComponent . Read why this is important here.

Add "else return null;" at the first if of your first option. Set to an array on your second option.

One option would be to ensure that your parent component always passes in a valid props.filters (empty array in the base case). Then your child component can blindly iterate over this.props.filters and render your <myFilterCOmponent /> .

Also look into using react React propTypes to ensure that a prop for your component is required, isArray etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM