2017-02-14 32 views
0

以下代碼給我這個錯誤:「無法讀取未定義的屬性'CityName'」。但是當我調試代碼時,數據狀態僅在第一次渲染時爲空,並且在那之後數據已經從API接收到數據。有沒有辦法強制渲染忽略第一個空狀態?狀態在第一次渲染時爲空

class profile extends Component { 
 

 
    constructor(props) { 
 
     super(props); 
 
     this.state = { 
 
      data :[], 
 
     }; 
 
     } 
 
    
 
    componentWillMount() { 
 
     axios.get(BASE_URL + 'user/' + 1) 
 
      .then(response => this.setState({data: response.data.Result})) 
 
      .catch(error => console.log(error)); 
 
    } 
 
    
 
    render() { 
 
     return (
 
      <View> 
 
       <Text>{this.state.data.Profile.CityName}</Text> 
 
      </View> 
 
     ); 
 
     } 
 
    }

回答

3

在第一渲染this.state.data是一個空數組,所以你應該把該控制到您的render方法,假設你的網絡調用返回一個數組:

render() { 
     const {data = []} = this.state; 
     return (
      data.map((record, index) => <View key={index}> 
            <Text>{record.Profile.CityName}</Text> 
           </View>) 
     ); 
     } 
    } 

否則,如果您的網絡請求返回一個對象,那麼它應該是這樣的:

render() { 
      //You may like to show loading indicator while retrieving data: 
      const {data = undefined} = this.state; 
      if(data) { 
       return (
         <View> 
         <Text>{this.state.data.Profile.CityName}</Text> 
         </View> 
       ); 
      }else{ 
       return <View><Text>Is loading</Text></View> 
      } 

     } 
+0

非常好,它的工作。但我仍然不明白是什麼在做const {data = undefined} = this.state。 – Nima

+0

這是ES6的「解構」功能。本質上它和'const data = this.state.data'是一樣的,所以只是將一個對象的字段明確分配給一個變量的較短版本。 – cubbuk

3

您已經定義data爲空數組,然後你在分配給對象。將它初始化爲空數組,然後將其初始化爲null

class profile extends Component { 

constructor(props) { 
    super(props); 
    this.state = { 
     data :null, 
    }; 
    } 

componentWillMount() { 
    axios.get(BASE_URL + 'user/' + 1) 
     .then(response => this.setState({data: response.data.Result})) 
     .catch(error => console.log(error)); 
} 

render() { 
    return (
     <View> 
      {this.state.data !== null ? <Text>{this.state.data.Profile.CityName}</Text> : <Text>Please Wait</Text>} 
     </View> 
    ); 
    } 
} 
+0

你有一個錯字我猜,渲染方法應該使用'this.state.data'而不是'this.props.data' – cubbuk

+0

@cubbuk是的,編輯它。謝謝。 – nrgwsth

+0

對不起,但它給了我同樣的錯誤。 @cubbuk代碼解決了我的問題。 – Nima