2016-11-22 52 views
8

我有一個場景,我將數據從reducer傳遞到我的反應狀態。檢查未定義在反應中

數據:

{ 
    "id": 1, 
    "title": "Test", 
    "content": { 
     "body": "sdfsdf" 
     "image": "http://example.com" 
    } 
} 

使用componentWillRecieveProps,這完全適用於檢索標題。

componentWillReceiveProps(nextProps) { 
    this.setState({ 
     title: nextProps.blog.title, 
    }) 
} 

但是,我很難檢索嵌套字段。當我這樣做:

componentWillReceiveProps(nextProps) { 
    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"] 
    }) 
} 

我得到這個錯誤:

enter image description here

未定義體的錯誤消失我點擊調試器和內容加載後。無論如何,我可以解決這個問題嗎?

我試圖檢查未定義這樣的:

if (typeof nextProps.blog.content["body"] != 'undefined'){ 

但是,這也不行,我相信這是因爲博客是不確定的。

+1

我覺得你的錯誤就在於,你的「身體」嵌套在「內容」 – naomi

+0

@naomi謝謝!我將我的代碼固定到blog.content而不是僅僅是內容,那是什麼意思?我仍然遇到同樣的錯誤。 – lost9123193

回答

5

你可以做的是檢查是否你的道具通過檢查最初還是沒有定義,如果nextProps.blog.content未定義或不是因爲你的身體是嵌套在它像

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"] 
     }) 
    } 
} 

你不需要使用類型檢查未定義,只是嚴格的運營商!==,它的值由它們的類型,以及作爲比較值

爲了檢查不確定的,你也可以使用typeof運營商像

typeof nextProps.blog.content != "undefined" 
+1

啊,我看到了,我在報價中放入了未定義的字符。這個伎倆。謝謝! – lost9123193

+1

沒問題。樂於幫助 –

0

我面對同樣的問題.....我用typeof()

if (typeof(value) !== 'undefined' || value != null) { 
     console.log('Not Undefind or Not Null') 
    } else { 
     console.log('Undefind or Null') 
} 

得到解決您必須使用typeof()來確定undefined