在内联代码中编写 if else 条件函数不会 return 任何值

Writing if else condition function in inline code doesn't return any value

为什么这个方法 return 没有任何值?

<span>{()=>{
    if(profile.age){
        return (2021 - profile.age)
    }
}}</span>

这和你创建一个不同的函数然后这样调用它不一样吗?

<span>{renderAge()}</span>

function renderAge(){
    if(profile.age){
        return (2021 - profile.age)
    }
}

我知道我可以使用 ? : 执行内联条件,但如果我有多个条件,那就很难了,而且我不想为此创建一个单独的函数。

老实说,我不知道有什么反应,但我还是试图找到一个可能的解决方案。给不了你很多解释(我知道不是很专业,但我花了一些时间,我还是回答了)。

This is a working example

class Test extends React.Component {
  render() {
    return <h1>Hello World! { 
        function(){ 
          if(1==1) {
            return 2021;
          } else {
            return 2022;
          }
        }() 
      } </h1>;
  }
}

ReactDOM.render(<Test />, document.getElementById('test'));

你真的不需要一个函数,一个三元表达式就可以了:

<span>{profile.age ? 2021 - profile.age : ''}</span>

但假设您需要一个函数,您可以使用 IIFE(立即调用的函数表达式),注意就地调用函数的额外括号:

<span>{(() => {
    if (profile.age){
        return (2021 - profile.age);
    }
})()}</span>

或者,更具可读性

<span>{((age) => {
    if (age) return 2021 - age;
})(profile.age)}</span>

在语义上等同于

// somewhere earlier
const renderAge = (age) => {
    if (age) return 2021 - age;
};

// and then
<span>{ renderAge(profile.age) }</span>