How to use if within a map return?

前端 未结 2 514
一个人的身影
一个人的身影 2021-01-31 16:54

I need to generate diffrent reactJS code based on datamodel but I get

In file \"~/Scripts/Grid.jsx\": Parse Error: Line 13: Unexpected token if (at lin

2条回答
  •  春和景丽
    2021-01-31 17:20

    You could also use a ternary (inline if/else) statement. It might look like this:

    row = this.props.cells.map(function(cell, i) {
        return (cell.URL != null && cell.URL.length > 0) ? 
            ({cell.Text}) :
            ({cell.Text})
    }.bind(this));
    

    or es6

    row = this.props.cells.map((cell, i) => (cell.URL != null && cell.URL.length > 0) ? 
            ({cell.Text}) :
            ({cell.Text})
    );
    

    but, for readability, I would suggest nilgun's answer.

    Although I would remove the else statement, since it is redundant. You could also remove the curly brackets, this is a matter of preference.

    row = this.props.cells.map(function(cell, i) {
        if(cell.URL != null && cell.URL.length > 0)
            return {cell.Text};        
        return {cell.Text};
    }.bind(this));
    

提交回复
热议问题