简体   繁体   中英

React: Returning iterated list from a stateless component

When I run this code, I get the error:

unexpected token, expected ,

All I am doing is calling a map method on an array:

const Available = ({prod}) => {
    let keys = Object.keys(prod)
    var filtered = keys.filter((item, index) => prod[item])
    return (
        {
            filtered.map((item, index) => {
            return <li><a>{item}</a></li>
        })
}
    )

}

Available.defaultProps = {
    Prod: {
        nuts: true,
        bolts: true,
        wiper: false,
        discbreak: true
    }
}

const Drop = (props) => {
    var style = {
        display: 'block'
    }
    if (props.isOpen) {
        return (
            <ul className="dropdown-menu" style={style}>
                <Available />
            </ul>
        )
    } else {
        return false
    }
}

I even tried changing 'Available' Component to as below.

const AvailableProducts = ({products}) => {
  debugger;
  let keys = Object.keys(products);
  var filtered = keys.filter((item,index)=>products[item]);

  filtered.map((item,index)=>{
    return <li><a>{item}</a></li>
  })
}

Now I end up getting error:

A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Where am i doing wrong? Can someone help on this?

In your second code, you are not returning anything, thus react throws that "A valid React element ..." error. Since filtered is an array, you should return filtered variable inside the div and you should be able to see your component without errors.

const AvailableProducts = ({products}) => {
  debugger;
  let keys = Object.keys(products);
  var filtered = keys.filter((item,index)=>products[item]);

  filtered = filtered.map((item,index)=>{
    return <li><a>{item}</a></li>
  });
  return <div>{filtered}</div>
}

Try this:

const Available = ({prod}) => {
  let keys = Object.keys(prod);
  var filtered = keys.filter((item)=>prod[item]);
  return (
    <div>
      {filtered.map((item)=><li><a>{item}</a></li>)}
    </div>
  );
}

You should return a single, valid React component (or null).

Reference: https://facebook.github.io/react/docs/react-component.html#render

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