2017-04-12 80 views
-1

我是React的新手,所以我只是想從我的wordpress網站API中提取數據。我得到一個通用的博客文章,將顯示this.state.post.link罰款,但不是任何呈現的數據。ReactJS顯示來自Wordpress API的數據

import React from 'react' 

export default React.createClass({ 

    getInitialState: function() { 
    return { 
     post: {}, 
    } 
    }, 

    componentDidMount: function() { 
    var _this = this; 
    $.get('http://somewebsite.net/wp-json/wp/v2/posts/1258', function(result) { 
     _this.setState({ 
     post: result 
     }); 
    }); 
    }, 

    render() { 
    console.log(this.state.post); 
    return <div className="single-post"> 
     <h1>{this.state.post.link}</h1> 
     <h1>{this.state.post.title.rendered}</h1> 
    </div> 
    } 
}); 

我從添加post.title.rendered得到此錯誤。

bundle.js:51835 Uncaught TypeError: Cannot read property 'rendered' of undefined 

這是用代碼顯示的內容console.log(this.state.post.title);

Object {rendered: "Example post"} 

所以我爲什麼CONSOLE.LOG this.state.post.title,它顯示對象與渲染,但然後如果我嘗試和顯示它會說標題是未定義的?

回答

3

定義title.rendered初始狀態爲空字符串。

this.state = { 
    post: { 
    title: { 
     rendered: '' 
    } 
    } 
... 
render() { 
    return (
    <div> 
     {this.state.post.title.rendered} 
    </div> 
) 
} 

OR

檢查狀態被渲染前的定義:

render() { 
    return (
    <div> 
     {this.state.post ? this.state.post.title.rendered : null } 
    </div> 
) 
} 
1

原因是要獲取來自API的數據,直到你沒有得到的數據,this.state.post.titleundefined,並且您試圖訪問的undefinedrendered,這就是爲什麼它是拋出錯誤:

Cannot read property 'rendered' of undefined

ajax呼叫asynchronous通話,這將需要時間來獲取數據和render方法之前被調用。

一種解決方案是,把支票this.state.post.title

render() { 
    console.log(this.state.post); 
    return <div className="single-post"> 
     <h1>{this.state.post.link}</h1> 
     <h1>{this.state.post.title && this.state.post.title.rendered}</h1> 
    </div> 
    } 

或保持完整的呈現,直到你沒有得到的數據,通過將支票上this.state.postrender方法。

更新 -

定義後的初始值null

getInitialState: function() { 
    return { 
     post: null, 
    } 
    }, 

然後檢查內部render方法後的價值,也不會呈現任何東西,直到你沒拿到迴應:

render() { 
    console.log(this.state.post); 

    if(!this.state.post) return null; 

    return <div className="single-post"> 
     <h1>{this.state.post.link}</h1> 
     <h1>{this.state.post.title.rendered}</h1> 
    </div> 
} 

注意:有一個問題,rendered密鑰必須存在於title之內,否則它也會引發相同的錯誤。

+0

好涼,讓我怎麼推遲渲染方法,直到加載數據?這似乎是對我來說最好的解決方案 – Callum

+0

@Callum檢查更新的答案,'返回null',直到你沒有得到的數據,它會工作:) –

+0

嗨謝謝,設置爲空的初始值爲null工作我。所以如果它在渲染方法中第一次返回null,是否意味着它會被調用兩次? – Callum

0

也許這將是有益的:

render() { 
    console.log(this.state.post); 
    var link = (this.state.post && this.state.post.link) ? this.state.post.link : ''; 
    var rendered = (this.state.post && this.state.post.title && this.state.post.title.rendered) ? this.state.post.title.rendered : ''; 

    return <div className="single-post"> 
     <h1>{link}</h1> 
     <h1>{rendered}</h1> 
    </div> 
    }