2017-05-28 3 views
0

リアクションネイティブアプリでデータを使用するためにAPIにクエリを実行しようとしていますが、 。基本的に、私は状態に格納されている市場オブジェクトにアクセスしようとしています。状態を調べると、マーケットオブジェクトが適切に設定されていることがわかります。しかし、マーケットオブジェクトで何かしようとするとすぐに、私はCannot read property 'markets' of nullというエラーが発生します。リアクションネイティブオブジェクトは状態にありますが、アクセスしようとすると未定義です

なぜこのようなことが起こり、この問題を解決するにはどうすればよいですか?

以下に問題を引き起こすコードが含まれています。私は何か提案を感謝します。

export default class cryptoTracker extends Component { 


    constructor(props) { 
    super(props); 

    this.opts = { 
     baseUrl: 'https://bittrex.com/api/v1.1', 
     apikey: 'APIKEY', 
     apisecret: 'APISECRET', 
    }; 
    this.updateMarkets(); 
    } 


    updateMarkets(){ 
    axios.get(this.opts.baseUrl + '/public/getmarkets').then((response) => { 
     this.setState({'markets' : response.data.result}); 
     } 
    ).catch((error) => { 
     console.log(error.name) 
     console.log("Error"); 
     }); 

    } 

render() { 
    console.log("The state is below"); 
    console.log(this.state); 
//This line causes the issue 
    console.log(this.state.markets); 


    return(
    <View> 
    </View>); 
} 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
    }, 
    instructions: { 
    textAlign: 'center', 
    color: '#333333', 
    marginBottom: 5, 
    }, 
}); 

AppRegistry.registerComponent('cryptoTracker',() => cryptoTracker); 
+0

コンソール出力を貼り付けることはできますか? –

答えて

0

理由は、あなたがconstructorstate変数を定義していない、です。 API呼び出しは、データを取得し、setStateを行うとき(つまりstatenull可能になる前まで)後のみstateレンダリング、利用できるようになりますので、非同期ことは、その前に実行されますと、それは価値this.state.makersにアクセスしようとするとき、それはありますエラーを投げる:

Cannot read property 'markets' of null

変更:

1.stateオブジェクトを定義し、その内部にmakersを定義し、このように:

constructor(props) { 
    super(props); 
    this.state = { 
     makers: {} 
    } 
    this.opts = { 
     baseUrl: 'https://bittrex.com/api/v1.1', 
     apikey: 'APIKEY', 
     apisecret: 'APISECRET', 
    }; 
} 

2.使用componentDidMountライフサイクル方法とは次のように、その内部のAPI呼び出しを実行します。コンポーネントの

componentDidMount(){ 
    this.updateMarkets(); 
} 

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

3.名は大文字で開始する必要があり、したがって、cryptoTrackerの代わりにCryptoTrackerを使用してください。

+0

ありがとうございました。私はコンストラクタでセットを設定しなければならない理由を理解していますが、 'setState'関数を使う代わりに直接セットする必要があるのはなぜですか?私はあなたが国家を決して決して決してしないと思った? – guribe94

+1

'setState'は' state'値を更新するために使用され、デフォルト値を割り当て、 'constructor'に' state'を定義します。はいいいえ私たちは決して 'コンストラクタ'のすぐ外側に 'state'を設定してはいけませんが、' constructor'は異なる値を初期化するために使われます。 –

関連する問題