React first rendering why prone TypeError: Can not read property 'XX' of undefined

  This question and we may be dismissive, hey, you gave the wrong face, you will not hate Well, in fact we have not seriously thought about the reason of it. First on a map error remaining thanks to compile. Figure not interested in old iron can be pulled directly to the bottom to see the conclusion

error:

 

 Code:

  Secondly, I then simplify the code to pull out for a walk (you can skip the picture, to see the conclusion)

 

 

 Strange place:

  In the author that line will throw an error on the beginning shot, comment out this line, and the rest will run normally

the reason:

  First, we note this.state.detail, the default value is given an empty string.

  Why should I deliberately do explain the empty string

  Have your attention the following code

 

The above image is the essence.

   this.state.detail.title first visit was in fact rendered '' .title, returns undefined, so the page is rendered to the string undefined
   But this.state.detail.author.loginname is different, this.state.detail.author already is undefined, which is equivalent to undefined.loginname, throw a TypeError
in conclusion:
  Property on access to the empty string will return undefined
    Properties on the access undefined throws a TypeError
    Null do not exist on access to property to get rid of a TypeError
   Pay attention to the '', null, what kind of results produced when obtaining property on undefined, the results appear to prevent uncontrolled  
 
solve:

   Before using a compatible property to do to prevent the error is thrown directly stuck page

  例如:this.state.detail.author.loginname 我们可以改为 this.state.detail.author&&this.state.detail.author.loginname

Guess you like

Origin www.cnblogs.com/suihang/p/11863735.html