thắc mắc ReactJS rendering confused ?

khangtictoc

Senior Member
Chào mọi người, mình mới học và tiếp cận ReactJS. Cho mình hỏi tại sao với code dưới

JavaScript:
function MailBox(props){
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

ReactDOM.render(
  <MailBox unreadMessages={[]} />,
  document.getElementById("root")
)

Thì nó render ra "Hello!"
Còn khi thay phần body của function Mailbox với
JavaScript:
function MailBox(){
 
    const count = 0;
    return (
      <div>
        { count && <h1>Messages: {count}</h1>}
      </div>
    );
 
}

ReactDOM.render(
  <MailBox />,
  document.getElementById("root")
)
Thì khi falsy expression diễn ra, nó sẽ render thành <div>0</div>
Theo document thì khi false nó sẽ return về 0. Trường hợp thứ 2 trên OK. Còn với trường hợp đầu tiên khi false, mình nghĩ nó sẽ render thành <div><h1>Hello</h1>0</div> chứ nhỉ ; và nó sẽ xuất ra "Hello0", nhưng thực tế lại xuất ra mỗi "Hello".

--Thanks mọi người đã đọc--
 
unreadMessages.length > 0 &&

Nếu bạn để

unreadMessages.length && thì sẽ ra 0

Hồi đầu mình mới học không chú ý cái này nên lâu lâu lại xuất hiện số 0 trên web mà không biết tại sao
 
Screen Shot 2022-03-03 at 23.22.04.png




Code:
Logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

Khi duyệt từ trái sang phải, nếu gặp falsy operand, thì ngắt điều kiện, và trả về cái value của falsy operand đó.

Quay lại ví dụ đầu của bác:

unreadMessages.length > 0 ==> cụm này là falsy operand, ngắt, và trả về value của nó là "false". Nói cách khác nguyên đoạn:

Code:
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }

sẽ evaluate thành "false". Mà giá trị "false" khi render lên DOM thì không có gì cả. Nên đó là lí do bác thấy html chỉ có "Hello".
 
View attachment 1043138



Code:
Logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

Khi duyệt từ trái sang phải, nếu gặp falsy operand, thì ngắt điều kiện, và trả về cái value của falsy operand đó.

Quay lại ví dụ đầu của bác:

unreadMessages.length > 0 ==> cụm này là falsy operand, ngắt, và trả về value của nó là "false". Nói cách khác nguyên đoạn:

Code:
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }

sẽ evaluate thành "false". Mà giá trị "false" khi render lên DOM thì không có gì cả. Nên đó là lí do bác thấy html chỉ có "Hello".
Hola, mình hiểu r ,tks bạn nhìu
 
Back
Top