Last updated on

jsx中用 && 可能有的坑

React 的数据处理

function Basic() {
  const text = "Hello, world!";
  const number = 0;
  const bool = false;
  const nothing = null;
  const notDefined = undefined;

  return (
    <div>
      <div>Text: {text}</div>
      <div>Number: {number}</div>
      <div>Boolean: {bool}</div>
      <div>Null: {nothing}</div>
      <div>Undefined: {notDefined}</div>
    </div>
  );
}

function ComplexObject() {
  const obj = {
    foo: 1,
  };
  const arr = [1, 2, 3];

  return (
    <div>
      {/* 这个会报错 */}
      {/* <div>Object: {obj}</div> */}
      <div>Array: {arr}</div>
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <Basic />
      <ComplexObject />
    </div>
  );
}
Text: Hello, world!
Number: 0
Boolean:
Null:
Undefined:
Array: 123

点这里直接看效果 CodeSandBox

&& 在 jsx 中的使用

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

返回第一个 falsy 值,如果全部 truthy 返回最后一个

Falsy 看这里 https://developer.mozilla.org/en-US/docs/Glossary/Falsy

ValueTypeDescription
nullNullThe keyword null — the absence of any value.
undefinedUndefinedundefined — the primitive value.
falseBooleanThe keyword false.
NaNNumberNaN — not a number.
0NumberThe Number zero, also including 0.00x0, etc.
-0NumberThe Number negative zero, also including -0.0-0x0, etc.
0nBigIntThe BigInt zero, also including 0x0n, etc. Note that there is no BigInt negative zero — the negation of 0n is 0n.
""StringEmpty string value, also including '' and ``.
document.allObjectThe only falsy object in JavaScript is the built-in document.all.

渲染中 && 和 number 要注意

{1 && 0 && <h1>1</h1>}

image

注意 0 被渲染了,可能不符合你的预期行为

Note

So,一般 jsx 里做渲染判断的值前面加 !! 转化下比较稳