Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 这两个if-else块和条件运算符块的区别是什么?_Reactjs_Conditional Statements - Fatal编程技术网

Reactjs 这两个if-else块和条件运算符块的区别是什么?

Reactjs 这两个if-else块和条件运算符块的区别是什么?,reactjs,conditional-statements,Reactjs,Conditional Statements,我认为这两个代码块具有相同的含义,但第二个代码不起作用,即使第一个代码起作用 第二个看起来没那么酷,但我认为它比第一个更容易理解 第一个是here()上非常简单的React实践代码的一部分 ,我对它做了一些修改 //1st const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature; const fahrenheit = scale === 'c' ? tryConvert(temper

我认为这两个代码块具有相同的含义,但第二个代码不起作用,即使第一个代码起作用

第二个看起来没那么酷,但我认为它比第一个更容易理解

第一个是here()上非常简单的React实践代码的一部分 ,我对它做了一些修改

//1st
  const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
  const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

//2nd  
  if(scale === 'f') {
    const celsius = tryConvert(temperature, toCelsius);
    const fahrenheit = temperature
  } else if (scale === 'c') {
    const celsius = temperature;
    const fahrenheit = tryConvert(temperature, toFahrenheit);
  } else {
    const celsius = temperature;
    const fahrenheit = temperature;
  }
运行包含第二个代码的my React代码时,控制台上会显示错误消息“未定义摄氏度”

在第二个代码中,我认为无论“比例”是什么,都必须定义“摄氏度”,因为在最后一个代码块中有else语句

这两种代码之间有什么区别

我很抱歉我的英语不好。。
谢谢你阅读我的问题

您的代码工作正常。问题是
const
(以及
let
)是所谓的。因此如果您在if/for/中定义它们,而它们只在该块中定义。

我想这段代码中没有这个问题。它可能就在那里,您可以访问变量/常量。 像这样在if-else-if块外部声明变量

 let celsius = temperature
 let fahrenheit = temperature
 if(scale === 'f') {
    celsius = tryConvert(temperature, toCelsius);
 }
 if (scale === 'c') {
    fahrenheit = tryConvert(temperature, toFahrenheit);
 } 
这样,你就不需要第三个街区了。如果您不喜欢使用条件运算符,并且希望使其更好,请尝试以下方法

 let celsius = temperature
 let fahrenheit = temperature
 if(scale === 'f') celsius = tryConvert(temperature, toCelsius);
 if (scale === 'c')  fahrenheit = tryConvert(temperature, toFahrenheit);

它可以将这些变量定义为if块外部的let,并在块内部更改其值(但我认为这不是一个很酷的代码。)谢谢!好吧,如果它看起来酷或不酷是在读者的眼中:)但是酷与可读性相比并不重要。您将希望能够在一年后快速理解您的代码所做的事情,并且其他人能够理解它。