简体   繁体   中英

React doesn't see mapped props

I have this message in browser: TypeError: data.map is not a function

I am passing an array from another component here as props. What I am doing wrong? Thank you in advance!

EDITED :

event-data.js

const months = ['January', 'February', 'March'];
const eventType = ['Party', 'Karaoke', 'Concert'];

const monthObject = [
  { id: 'sort-by-month' },
  { name: 'By month' },
  { values: months },
];

const eventObject = [
  { id: 'sort-by-category' },
  { name: 'By category' },
  { values: eventType },
];

const eventData = { monthObject, eventObject };

event-filter-bar.js

import eventData from '../../data/event-data';

class EventFilterBar extends React.Component {
  render() {
    return (
      <FilterToolbar data={eventData} />
    );
  }
}

filter-toolbar.js

class FilterToolbar extends Component {
  render() {
    const { data } = this.props;
    return (
      <ButtonToolbar className="justify-content-center">
        <DropdownMaker data={data} />
        <DropdownWithDate />
        <ResetButton />
      </ButtonToolbar>
    );
  }
}

FilterToolbar.propTypes = {
  data: PropTypes.array.isRequired,
};

dropdown-maker.js

class DropdownMaker extends Component {
  render() {
    const { data } = this.props;
    const eventFilters = data.map((e) => (
      <DropdownMenu
        id={e.id}
        name={e.name}
        values={e.values}
        key={e.id}
      />
    ));
    return (
      { eventFilters }
    );
  }
}

DropdownMaker.propTypes = {
  data: PropTypes.array.isRequired,
};

Check if the data is actually populated or not before map through it.

class DropdownMaker extends Component {
  render() {
    const { data } = this.props;
    const eventFilters = (data && data.length > 0) && data.map((e) => (
      <DropdownMenu
        id={e.id}
        name={e.name}
        values={e.values}
        key={e.id} //<-- don't forget to add a unique key prop while use loop
      />
    ));
    return (
      { eventFilters }
    );
  }
}

DropdownMaker.propTypes = {
  data: PropTypes.array.isRequired,
};

Feel free to comment if it's not working.

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