2017-03-06 21 views
0

オブジェクトfirstOccurrenceに配列extrasが含まれています。これは最初は空の配列に設定されています。次に、AJAXリクエストを行い、配列全体が置換されずに空であることを除いて正常に動作するオブジェクトfirstOccurrence全体を置き換えます。React:オブジェクトを更新した後、オブジェクト内の配列が置換されない

アレイを含むオブジェクト全体をどのように置き換えることができますか?

import React, { Component } from 'react'; 
import { StyleSheet, View, Text } from 'react-native'; 
import axios from 'axios'; 

export default class Job extends Component { 
    state = { 
    firstOccurrence: { 
     customer: {}, 
     job: {}, 
     extras: [] 
    } 
    }; 

    componentWillMount() { 
    axios.get(
     `http://api.test.dev:5000/jobs/1.json`, 
     { 
     headers: { Authorization: 'Token token=123' } 
     } 
    ).then(response => { 
     console.log(response.data); 
     this.setState({ 
     firstOccurrence: response.data 
     }) 
    }); 
    } 

    render() { 
    return (
     <View> 
     <View> 
      <Text>{this.state.firstOccurrence.customer.firstName} {this.state.firstOccurrence.customer.lastName}</Text> 
     </View> 
     {this.state.firstOccurrence.extras.length > 0 && 
      <View> 
      <Text>Extras: {this.state.firstOccurrence.extras}</Text> 
      </View> 
     } 
     </View> 
    ); 
    } 
} 

JSONレスポンス:

enter image description here

+1

JSON応答データを投稿できますか? – Pineda

+0

@Pineda質問に追加しました – migu

+0

期待される出力は何ですか?代わりに何が起こりますか? – Pineda

答えて

1

あなたが代わりにコンストラクタの機能componentDidMountにリクエストを行う必要があります

constructor() { 
    super(); 

    this.state = { 
     firstOccurrence: { 
     customer: {}, 
     job: {}, 
     extras: [] 
     } 
    }; 
} 

    componentDidMount(){ 
    axios.get(
     `http://api.test.dev:5000/crew/v1/jobs/1.json`   
    ).then(response => {this.setState({ 
     firstOccurrence: response.data 
    })}); 
    } 

それはwill be called when the component is mounted、あなたが設定できるようになりますその状態が再描画をトリガーします。 firstOccurrenceには、最初のレンダリングでコンストラクタで設定した初期値があり、API呼び出しが完了して新しい値が設定されると、コンポーネントが再レンダリングされることに注意してください。

+0

AJAXリクエストをコンストラクタから移動しましたが、それでも動作しません – migu

関連する問題