2017-03-06 32 views
0

我有一個對象firstOccurrence,它包含一個數組extras,我最初設置爲一個空數組。然後我做一個AJAX請求,並替換整個對象firstOccurrence,它可以正常工作,但數組不會被替換並保留爲空。反應:更新對象後,對象內的數組不會被替換

我該如何更換包含該數組的整個對象?

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