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

あなたのネットワーク呼び出しが配列を返すと仮定すると、あなたの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の 'destructuring'機能です。基本的には 'const data = this.state.data'と同じです。したがって、オブジェクトのフィールドを変数に明示的に割り当てる短いバージョンです。 – cubbuk

3

あなたはdataとして空の配列を定義して、その後、あなたはそれがオブジェクトに割り当てます。空の配列として初期化するのではなく、nullとして初期化します。最初this.state.dataレンダリングで

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.props.data'ではなくthis.state.dataを使用する必要があります – cubbuk

+0

@cubbukうん、それを編集しました。ありがとう。申し訳ありませんが、それは私に同じエラーを与えました。 – nrgwsth

+0

@cubbukコードが私の問題を解決しました。 – Nima

関連する問題