2017-03-06 101 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

相关问题