2016-10-13 6 views
0

Axisを使用してAJAX呼び出しを行い、データは未定義に戻り、数秒後に配列を操作します。私はcomponentDidMountとcomponentWillMountを試しました。私は小道具として初期状態のコンストラクタを作ろうとしました。 React.createClassを使用しない限り、getInitial状態は推奨されません。反応するajax呼び出しは最初は定義されていません

ここに私のコードがあります。何か助けてください!

アクション/ index.js

import axios from 'axios'; 
import { FETCH_STRAINS } from './types'; 
const ROOT_URL = `https://www.cannabisreports.com/api/v1.0/strains?sort=name&page=3`; 

export function fetchStrains() { 
    return dispatch => { 
     axios.get(ROOT_URL) 
      .then(response => { 
       dispatch({ 
        type: FETCH_STRAINS, 
        payload: response.data.data 
       }) 
      }) 
      .catch(error => console.log(error)); 
    } 
} 

減速/ index.js

import { FETCH_STRAINS } from '../actions/types'; 
import initialState from './initialState'; 
export default function(state = initialState.strains, action) { 
    switch(action.type) { 
     case FETCH_STRAINS: 
      return { ...state, strains: action.payload }; 
     default: 
      return state; 
    } 
} 

あなたは非同期アクション& thunk-インポートする必要性を使用する必要が

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import * as actions from './actions'; 
import './App.css'; 

class App extends Component { 
    componentWillMount() { 
     this.props.fetchStrains(); 
    } 

    render() { 
    return (
     <div className="App"> 

     {this.props.strains === undefined ? console.log("this is undefined") : console.log(this.props.strains)} 

     </div> 
    ); 
    } 
} 

function mapStateToProps(state) { 
    return { strains: state.strains.strains } 
} 

export default connect(mapStateToProps, actions)(App); 

答えて

0

あなたの問題は、コードが間違っているためではありません。あなたはそれを正しくやっているように見えます。

問題は、あなたのアプリが存在し、すべてのデータを用意して前に表示されていることです。アクシオスコールは完了するまでに非常に時間がかかります。それが完了するまで、あなたのアプリはあなたが好きかどうかにかかわらず、何かをユーザーに表示しています。

ので、起動やデータの到着の間、strainsundefinedになるだろう。ユーザーが待っている間にユーザーに何を表示するかを決める必要があります。一般的な解決策はスピナーです。

0

app.jsミドルウェアを使用しています。

export function fetchStrains() { 

// Thunk middleware knows how to handle functions. 
// It passes the dispatch method as an argument to the function, 
// thus making it able to dispatch actions itself. 

return function (dispatch) { 

// First dispatch: the app state is updated to inform 
// that the API call is starting. 

// The function called by the thunk middleware can return a value, 
// that is passed on as the return value of the dispatch method. 

// In this case, we return a promise to wait for. 
// This is not required by thunk middleware, but it is convenient for us. 

axios.get(ROOT_URL) 
     .then(response => { 
      dispatch({ 
       type: FETCH_STRAINS, 
       payload: response.data.data 
      }) 
     }) 
     .catch(error => console.log(error)); 

} 
} 
関連する問題