简体   繁体   中英

How to check if a property is null in reactjs?

I am here with a basic question. If I directly compare variables then I can get defined results. But I can not check if a passed value as property is null or undefined. Because it is showing never as null or undefined. So conditional checking not working. So please advice me, how to check if a property is undefined or null.

import { memo, useRef } from "react"; 

const MyComponent = (myList) => {
  const renderTimes = useRef(0);

  return (
    <div>
      {renderTimes.current++}

      <div>Rendered : {renderTimes.current} times.</div>
 

      {console.log(
        "block. Is it null? : ",
        myList === null,
        " is it undefined ? ",
        myList === undefined,
        "Check type:",
        typeof myList === "undefined"
      )}
    </div>
  );
};

export default MyComponent;

在此处输入图像描述

<MyComponent myList={undefined} />

If I pass nothing or even I passed named property as null and undefined both the time it shows same result.

You can modify modify your code as such:

 import { memo, useRef } from "react"; const MyComponent = (props) => { const renderTimes = useRef(0); // Checks if the "myList" element is defined if(this.props.myList === undefined) { console.log('myList is not defined') } return ( <div> {renderTimes.current++} <div>Rendered: {renderTimes.current} times.</div> {console.log( "block. Is it null? : ", {{ props.myList }} === null, " is it undefined? ", {{ props.myList }} === undefined, "Check type:", typeof {{ props.myList }} === "undefined" )} </div> ); }; export default MyComponent;

In short: your 'myList' variable is actually the props object - it would never show a null / undefined value (as it's an object).

The right way to pass values to components (from a parent component) is via the props object. At the child component, you get them using this way ( NOTE: without this. as this is a functional component ):

Using the example you supplied:

Parent comp (what you've done there was just fine):

<MyComponent myList = {...} />

Child comp:

{props.myList}

(Or without the brackets when used outside the return block.)


By the way, if you'd like to create a render counter, the right way to do that is performing the renderCounter++; command outside the return block (in which you will then display the updated variable), ie,

...

    renderTimes.current++;
  return (
    <div>
      {renderTimes.current}

...

I think you might be getting wrong outputs from the counter this way, not sure though.

Remember that useRef() does not re-render the component, while useState() does (I don't know what exactly you were trying to achieve there, I'm just mentioning it fwiw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM