2017-02-14 97 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