2017-11-05 18 views
-3

render()の前にサーバーからデータをダウンロードし、HTMLでカバーする必要があります。エラーがあります。this.state.newsは未定義ですです。 getInitialStatecomponentWillMountの例を試しましたが、動作しません。 AJAX要求からJSONの反応の初期状態

import { Component } from 'react' 

import { Link } from 'react-router-dom' 
import $ from 'jquery' 

export default class News extends Component{ 
constructor(props){ 
    super(props); 
    this.state = { news: []}; 
} 

componentWillMount() { 
    const setState = this.setState; 
    $.ajax({ 
     type: "GET", 
     url: "localhost/news", 
     data: {}, 
     success: function(data){ 
      setState(() => data); 
     }, 
    }); 
} 

render(){ 
    let news = this.state.news; 
    return(
     news.map(function(n, i){ 
      return <div class="news-block"> 
       <Link to={`/news/post/${n.id}`}><h5>{n.theme}</h5></Link> 
       <small> 
        <Link to={`/user/${n.author}`}> 
         {n.author} 
        </Link>, {n.date_of_create} 
       </small> 
       <p>{n.about}</p> 
      </div>; 
     }) 
    ); 
} 
} 

例:

{ 
    "news": [ 
    { 
     "id": "35268", 
     "theme": "The,e", 
     "author": "alex", 
     "date_of_create": "2000-01-01 00:00:54", 
     "public": "0", 
     "about": "sometjing", 
     "source": "some news" 
    } 
    ] 
    } 
+1

は –

答えて

0

私はあなたがそのコードにはいくつかの問題を持っていると思います。

最初は、非同期データを使って作業しているときに同期方法でデータを取得しているように動作していることです。

あなたの州の属性「ニュース」にアクセスしていますが、決して割り当てられていないということです。あなたはこのような何かを試してみてください

import { Component } from 'react' 

import { Link } from 'react-router-dom' 
import $ from 'jquery' 

export default class News extends Component{ 
constructor(props){ 
    super(props); 
    this.getNews = this.getNews.bind(this); 
} 

componentWillMount() { 
    const setState = this.setState.bind(this); 
    $.ajax({ 
     type: "GET", 
     url: "localhost/news", 
     data: {}, 
     success: function(data){ 
      setState(() => data); 
     }, 
    }); 
} 

render(){ 
    let news = this.state.news; 
    return(
     news.map(function(n, i){ 
      return <div class="news-block"> 
       <Link to={`/news/post/${n.id}`}><h5>{n.theme}</h5></Link> 
       <small> 
        <Link to={`/user/${n.author}`}> 
         {n.author} 
        </Link>, {n.date_of_create} 
       </small> 
       <p>{n.about}</p> 
      </div>; 
     }) 
    ); 
} 
} 
+0

新しいエラーが "this.setStateがnullの" https://ru.stackoverflow.com/を英語で聞いて、またはご使用ください。どうしましたか? –

+0

更新されたコードを共有できますか? – dlopez

+0

私はコードを更新しました –

関連する問題