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

问题描述 投票:10回答:3

我正试着把头围绕在JSX上。我发现了一个非常奇怪的行为。这是我的代码:

const name = undefined;
const myFunc = () => undefined;
let template = (
  <div>
    {myFunc()}
    {name}
    {undefined}
  </div>
);

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

输出是一次:undefined

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

javascript reactjs jsx
3个回答
7
投票

这是因为JSXReact.createElement(component, props, ...children)的语法糖 它将忽略这些类型(请参阅DOCS):

  • 布尔
  • 未定义
  • 空值

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

window.name将使用toString方法将所有值转换为其字符串表示形式。

如果你将变量更改为其他东西,让我们说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>

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


0
投票

这里的输出在你的div之间是空的。我把这段代码放到jsfiddle来演示:

const name = undefined;
const myFunc = () => undefined;
let template = (
  <div>
    {myFunc()}
    {name}
    {undefined}
    Hello world
  </div>
);

请注意,您可以看到的是我添加的“Hello world”。


0
投票

这是因为全局变量name是属性window.name并且将始终是一个字符串。

window.name将使用toString方法将所有值转换为其字符串表示形式。

name = undefined
foo = undefined
console.log('`name` is a', typeof name, ', but `foo` is a', typeof foo)

使用不同的全局变量名称,它应该按预期工作。但是,您通常不应该在模板中使用全局常量。

© www.soinside.com 2019 - 2024. All rights reserved.