2016-10-19 7 views
0

Reduxを使用してAPIからデータを取得しようとしています。私のコードは次のようになります。redux APIからデータを取得

処置:

// Import libraries 
import axios from 'axios'; 

// Import types 
import { 
    GET_ALL_PICKS 
} from './types'; 

export const getAllPicks = ({ token }) => { 
    const getPicks = (dispatch) => { 
    axios({ 
     method: 'get', 
     url: 'http://myapi/', 
     headers: { 
     Authorization: `Bearer ${token}` 
     } 
    }) 
    .then((response) => { 
     console.log(response.data); // First log here returns data just fine 
     dispatch({ 
     type: GET_ALL_PICKS, 
     payload: response.data 
     }); 
    }) 
    .catch((error) => { 
     console.log(error); 
    }); 
    }; 

    return getPicks; 
}; 

リデューサー:

// Import types 
import { 
    GET_ALL_PICKS 
} from '../actions/types'; 

// Set Initial State 
const INITIAL_STATE = { 
    allPicks: {}, 
    loading: false, 
    error: '' 
}; 

// Make pick reducers 
export default (state = INITIAL_STATE, action) => { 
    switch (action.type) { 
    case GET_ALL_PICKS: 
     return { ...state, allPicks: action.payload }; // Logging action.payload here returns data just fine 
    default: 
     return state; 
    } 
}; 

コンポーネント:私はアプリを実行すると

// Import Libraries 
import React, { Component } from 'react'; 
import { Text } from 'react-native'; 
import { connect } from 'react-redux'; 
import { 
    getAllPicks 
} from '../actions/picks'; 

// Make Component 
class HomeScreen extends Component { 
    // Fetch Data 
    componentWillMount() { 
    const { token } = this.props; 

    this.props.getAllPicks({ token }); 
    } 

    // Test response 
    componentDidMount() { 
    console.log(this.props.allPicks); // This log returns empty object, why?! 
    } 

    render() { 
    return (
     <Text>Test</Text> 
    ); 
    } 
} 

const mapStateToProps = ({ auth, picks }) => { 
    const { token } = auth; 
    const { allPicks } = picks; 

    return { 
    token, 
    allPicks 
    }; 
}; 

export default connect(mapStateToProps, { getAllPicks })(HomeScreen); 

は、私はアクションconsole.logでデータを参照してください私が減速機でconsole.log(action.payload)を実行すると、データはうまく表示されますが、コンポーネントI私のレデューサーのデータを正しく接続していないことを示唆する空の配列を参照してください。ここでは、ログのスクリーンショットだ:

return Object.assign({}, state, { 
    allPicks: action.payload 
    }); 

をしかし、再び、私は同じ結果を得た:

enter image description here

私はまた、いくつかのグーグルでの後、私の減速でこれを試してみました。誰か私が間違っていることを私に説明することはできますか?

答えて

3

コンポーネントライフサイクルとAPIライフサイクルが混乱しています。実際に

、何が起こっていることは次のとおりです。

  • componentWillMount
  • getAllPicks
  • componentDidMount(その時点で、APIが返していませんでした、ピックが空である)
  • [... APIが返るのを待つ]
  • APIはデータとともに返されますが、遅すぎます

機能で「選択」状態を確認する必要があります。これは、connect()機能のおかげで状態が変わるたびに(APIが返ってくるときに)更新されます。

componentWillUpdateを使用してピックが正しく更新されていることを確認することもできますが、componentDidMountではなく、更新中の小道具とは関係ありません。

関連する問題