reactjs – 为什么React只在它们是变量时将undefined / boolean / null解析为string?

我正试图围绕JSX.
我发现了一个非常奇怪的行为.
这是我的代码
const name = undefined;
const myFunc = () => undefined;
let template = (
  <div>
    {myFunc()}
    {name}
    {undefined}
  </div>
);

ReactDOM.render(template,document.querySelector("#root"));

输出是一次:
未定义

为什么const“name”是唯一解析为字符串的未定义值?
这个const和其他两个表达式有什么区别?
(与Boolean和null相同.)
请在此处查看我的代码codepen

这是因为JSX是 React.createElement(component,props,...children)的语法糖
它将忽略这些类型(见 DOCS):

>布尔值
>未定义
> null

我只是意识到这只发生在像codepen这样的编辑器上,因为它们在全局上下文和window.name will always be a string中运行代码.

window.name will convert all values to their string representations by
using the toString method.

如果您将变量更改为其他内容,请假设name1的行为符合预期.

const name1 = undefined;
const myFunc = function(){return undefined};
let template = (
  <div>
    {name1}
    {undefined}
    {myFunc()}
  </div>
);

顺便说一下,stack-snippets表现相同:

console.log('name is ',name);
const name = undefined;
console.log('and Now name is ',name);
const name1 = undefined;
const myFunc = function(){return undefined};
let template = (
  <div>
    {name}
    {name1}
    {undefined}
    {myFunc()}
  </div>
);

ReactDOM.render(template,document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

其他编辑器如codesandBox或jsfiddle将把代码包装在一个函数中,因此与window.name没有冲突.

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...