最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Expected to return a value at the end of arrow function with if statement - Stack Overflow

programmeradmin4浏览0评论

I am having this code.

{
  Object.keys(_.get(order, "customer", {})).map((key) => {
    if (key !== "defaultOption" && customer[key] !== "") {
      return (
        <option key={key} value={key}>
          {_.startCase(key)}
        </option>
      );
    }
  });
}

And having below warning

  Line 885:96:  Expected to return a value at the end of arrow function  array-callback-return

I know because I am using if statement inside the map function. So, How to get rid of the error?

I am having this code.

{
  Object.keys(_.get(order, "customer", {})).map((key) => {
    if (key !== "defaultOption" && customer[key] !== "") {
      return (
        <option key={key} value={key}>
          {_.startCase(key)}
        </option>
      );
    }
  });
}

And having below warning

  Line 885:96:  Expected to return a value at the end of arrow function  array-callback-return

I know because I am using if statement inside the map function. So, How to get rid of the error?

Share Improve this question asked May 16, 2020 at 13:24 Dark KnightDark Knight 1,0936 gold badges26 silver badges50 bronze badges 3
  • 1 Does this answer your question? Expected to return a value at the end of arrow function – wentjun Commented May 16, 2020 at 13:39
  • @wentjun Hmm. But got more innovative answers here. – Dark Knight Commented May 16, 2020 at 13:41
  • Yup agree. Just adding more options for you to choose from :) – wentjun Commented May 16, 2020 at 13:44
Add a ment  | 

8 Answers 8

Reset to default 3

return something after the if statement (even if it is an empty string).

You might want to filter such values out of the array afterwards (or just filter the array first instead of using an if).

What ESLint is telling you is that if the condition is false, your map callback doesn't return anything, so the array that map creates will have undefined there. That's often a mistake, rather than something you're doing intentionally.

Have the function return something whether the condition is true or false. For instance, you might return null if the condition is false, if you don't want React to render anything for that entry.

But instead, I'd probably filter, then map:

{
  Object.keys(_.get(order, "customer", {}))
  .filter((key) => key !== "defaultOption" && customer[key] !== "")
  .map((key) => (
      <option key={key} value={key}>
        {_.startCase(key)}
      </option>
    )
  )
}

Side note: I've removed the ; after map(/*...*/) in the above because it looks like it's inside a JSX expression. ; is a statement terminator, which you can't have inside a JSX expression. (Of course, if that isn't a JSX expression, ignore that change, though that would mean the code was creating options that it never used... :-) )

The root cause of the problem is due to return statement being inside an if condition.

This means that the function will return only when the condition is true.

The behaviour for condition being false also must be defined in order to resolve the issue.

This can be achieved in 3 ways:

  • Add a filter to obtain only the interesting values in the map (Remended)

  • Add an else block to return something when condition fails

  • or by adding an explicit return at the final line of the code block.

Here is an example of the suggested change:

Option 1: Add a filter to get a map of interesting values only (remended)

Object.keys(_.get(order, "customer", {}))
    .filter( 
        (interestingValue) => (
            interestingValue !== "defaultOption" && 
            customer[interestingValue] !== ""
        ) 
    )
    .map( 
        (key) => (
            <option key={key} value={key}>
                {_.startCase(key)}
            </option>
        )
    )

Option 2: Add an else block

Object.keys(_.get(order, "customer", {}))
    .map( (key) => {
            if (key !== "defaultOption" && customer[key] !== "") {
                return (
                    <option key={key} value={key}>
                        {_.startCase(key)}
                    </option>
                )
            } else {
                return (
                    <div>condition failed</div>
                )
            }            
        }
    )

Option 3: Add an explicit return at the end of the block

Object.keys(_.get(order, "customer", {}))
    .map( (key) => {
            if (key !== "defaultOption" && customer[key] !== "") {
                return (
                    <option key={key} value={key}>
                        {_.startCase(key)}
                    </option>
                )
            }
            return undefined
        }
    )

You have to return something for map() to work with. You cannot 'skip' values with map().

Try returning null and then applying filter to filter out those null values afterwards.

Just add return null after if statement.

You can convert this into a loop.

{
    (()=>{
        let arr=[];
        const keys = Object.keys(_.get(order, "customer", {}));
        for(let key of keys){
            if (key !== "defaultOption" && customer[key] !== "") {
                arr.push(<option key={key} value={key}>
                    {_.startCase(key)}
                </option>)
            }
        }
        return arr;
    })()
}

Issue is there is no else block, what if condition got false

map function expects some value in returns

{
  Object.keys(_.get(order, "customer", {})).map((key) => {
    if (key !== "defaultOption" && customer[key] !== "") {
      return (
        <option key={key} value={key}>
          {_.startCase(key)}
        </option>
      );
    } else { 
        return null;  // <----- You were missing this
    }
  });
}

OR

{
    Object.keys(_.get(order, "customer", {}))
    .filter((key) => (key !== "defaultOption" && customer[key] !== "") )
    .map((key) => (
        <option key={key} value={key}>
          {_.startCase(key)}
        </option>
      );
    );
}

You need to return value outside of your if statement within your map function. Since you are not doing that you are being warned by eslint.

{
  Object.keys(_.get(order, "customer", {})).map((key) => {
    if (key !== "defaultOption" && customer[key] !== "") {
      return (
        <option key={key} value={key}>
          {_.startCase(key)}
        </option>
      );
    }
    return null;  // return value here 
  });
}

Now you can return null from within map function when your condition doesn't match as react doesn't render null values

发布评论

评论列表(0)

  1. 暂无评论