2017-05-06 7 views
0
let user = { 
    "id":14, 
    "email":"[email protected]", 
    "first_name":"Fry", 
    "last_name":"Hamson", 
    "posts":[ { id: 28, 
    dog_name: 'Skip', 
    description: 'yub nub! yub nub!', 
    image_url: 'https://www.k9ofmine.com/wp-content/uploads/2014/09/ewok-dog-costume.jpg' }, 
    { id: 29, 
    dog_name: 'Champ', 
    description: 'You were my brother! I loved you!', 
    image_url: 'http://stories.barkpost.com/wp-content/uploads/2014/04/dog-star-wars-costume-12.jpg' }, 
    { id: 32, 
    dog_name: 'Baxter', 
    description: 'Give me treats, you will...', 
    image_url: 'http://www3.pictures.zimbio.com/mp/r_Mf-uluvPrx.jpg' } ] 

上記のコードスニペットからデータを取得できません。私はロジックがすべて設定されていますが、React Componentにどこに配置するかは分かりません。ここに私のReactページがあります。フェッチでコメントアウトされました。Rails APIからのReactJSフェッチ:配列内のハッシュを返します。

class Profile extends Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     names: [], 
     descriptions: [], 
     images: [] 
    } 
    this.getProfileData = this.getProfileData.bind(this) 
    } 

    componentDidMount() { 
    this.getProfileData() 
    } 

    getProfileData() { 
    fetch(`/api/v1/users`, {credentials: 'same-origin'}) 
    .then(response => response.json()) 
    .then(user => { 
     this.setState({ 
     id: user.id, 
     firstName: user.first_name, 
     lastName: user.last_name, 
     posts: user.posts 
    // for (i=0; i<user.posts.length; i++) { 
    // names.push(user.posts[i].dog_name) 
    // descriptions.push(user.posts[i].description) 
    // images.push(user.posts[i].image_url) 
    // } 
     }) 
    }) 
    } 

    render() { 
    return(
     <div> 
     <ProfileTile /> 
     </div> 
    ) 
    } 
} 

私はかなりの周りに移動してきたようにコメントアウトロジックは、SETSTATEで正しくフォーマットされていません知っています。しかし、私はこの反復を実装する方法について、atmを失っています。私はアクティブ:モデル:シリアライザをRails側で使用しています。 ご協力いただきありがとうございます。

答えて

1

名前、説明、状態の画像を表示するには、マップ関数を使用して検索する必要があります。

getProfileData() { 
    fetch(`/api/v1/users`, {credentials: 'same-origin'}) 
    .then(response => response.json()) 
    .then(user => { 
     this.setState({ 
     id: user.id, 
     firstName: user.first_name, 
     lastName: user.last_name, 
     posts: user.posts, 
     names: user.posts.map(u => u.dog_name), 
     descriptions: user.posts.map(u => u.description), 
     images: user.posts.map(u => u.image_url) 
     }); 
    }); 
    } 
関連する問題