Checking for Undefined In React

前端 未结 4 628
囚心锁ツ
囚心锁ツ 2020-12-29 20:10

I have a scenario where I\'m passing data from a reducer into my react state.

data:

{
    \"id\": 1,
    \"title\": \"Test\",
    \"content\": {
            


        
相关标签:
4条回答
  • 2020-12-29 20:25

    What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

    componentWillReceiveProps(nextProps) {
    
        if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
           console.log("new title is", nextProps.blog.title);
           console.log("new body content is", nextProps.blog.content["body"]);
           this.setState({
               title: nextProps.blog.title,
               body: nextProps.blog.content["body"]
           })
        }
    }
    

    You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

    In order to check for undefined, you can also use the typeof operator like

    typeof nextProps.blog.content != "undefined"
    
    0 讨论(0)
  • 2020-12-29 20:29

    In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:

    if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
        //
    }
    

    And, when an undefined , empty or null value is not expected; you can make it more concise:

    if (nextProps.blog && nextProps.blog.content) {
        //
    }
    
    0 讨论(0)
  • 2020-12-29 20:34

    You can check undefined object using below code.

    ReactObject === 'undefined'

    0 讨论(0)
  • 2020-12-29 20:44

    I was face same problem ..... And I got solution by using typeof()

    if (typeof(value) !== 'undefined' && value != null) {
             console.log('Not Undefined and Not Null')
      } else {
             console.log('Undefined or Null')
    }
    

    You must have to use typeof() to identified undefined

    0 讨论(0)
提交回复
热议问题