Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jsx中用 && 可能有的坑 #90

Open
sedationh opened this issue Jul 4, 2024 · 0 comments
Open

jsx中用 && 可能有的坑 #90

sedationh opened this issue Jul 4, 2024 · 0 comments

Comments

@sedationh
Copy link
Owner

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

Value Type Description
null Null The keyword null — the absence of any value.
undefined Undefined undefined — the primitive value.
false Boolean The keyword false.
NaN Number NaN — not a number.
0 Number The Number zero, also including 0.00x0, etc.
-0 Number The Number negative zero, also including -0.0-0x0, etc.
0n BigInt The BigInt zero, also including 0x0n, etc. Note that there is no BigInt negative zero — the negation of 0n is 0n.
"" String Empty string value, also including '' and ``.
document.all Object The only falsy object in JavaScript is the built-in document.all.

渲染中 && 和 number 要注意

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

image

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

Note

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant