Render Method Breaking When Mapping Value Inside

2019-07-25 03:58发布

问题:

I have a component (a dropdown list), which should populate the list based on an array which was passed in from another component as the "classes" prop. To make it as efficient as possible, I'm attempting to use Object.keys and Array.prototype.map methods to loop through my array, populate the list, and render. But, whenever I added this component, it causes my entire application to not render at all. I've listed my render method below.

Render Method:

export default React.createClass({

    change: function(){
        console.log(this.props.classes);
    },

    render: function(){

        return(
            <div>

             <select onChange = {this.change}>
             {
                Object.keys(this.props.classes).map(value, key =>{

                return <option key = {key}>{value}</option>
                }
             )}
              </select>
            </div>

        )

    }

});

回答1:

The callback parameters need extra parenthesis I think:

export default React.createClass({

    change: function(){
        console.log(this.props.classes);
    },

    render: function(){

        return(
            <div>

             <select onChange = {this.change}>
             {
                Object.keys(this.props.classes).map((value, key) =>{

                return <option key = {key}>{value}</option>
                }
             )}
              </select>
            </div>

        )

    }

});


回答2:

When you use ES2015 arrow functions and you have more then one parameter, you need to put parentheses around the parameters, like this:

Object.keys(this.props.classes).map((value, key) => {
   return <option key={key}>{value}</option>
 }

You can omit the parentheses only when you have one parameter.