2017-05-03 128 views
0

我一直在製作一個使用Google Sheet API和React/Redux的應用程序。使用Google Sheet API v4的React/Redux不提取數據

如果我從組件本身點擊API,它可以工作,但是在通過Redux獲取數據時我遇到了問題。

這是代碼

行動的創建者:

export function fetchList() { 
    let data = null; 
    gapi.client.sheets.spreadsheets.values.get({ 
     spreadsheetId: FULL_LIST_ID, 
     range: RANGE 
    }).then((response) => { 
     data = response.result.values; 
    }, (response) => { 
     throw response.result.error.message; 
    }); 

    return { 
     type: FETCH_LIST, 
     payload: data 
    } 
} 

減速機:

export default function(state = INITIAL_STATE, action = {}) { 
    switch (action.type) { 
     case FETCH_LIST: 
      return { ...state, list: action.payload }; 
     default: 
      return state; 
    } 
} 

組件:

import React from 'react'; 
import { connect } from 'react-redux'; 
import { fetchList } from '../../actions/index.jsx'; 
export class DropdownList extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { res: null } 
     // this._fetchList = this._fetchList.bind(this); 
    } 

    componentWillMount() { 
     // this should fetch the data from Redux 
     this.props.fetchList(); 
     // so that when 
     console.log(this.props); 
     // I should see the values attached to the payload 
     // instead this is fetching the data from the API hit here 
     this._fetchList(); 
    } 

    // Here I'm hitting the API from the component 
    _fetchList() { 
     gapi.client.sheets.spreadsheets.values.get({ 
      spreadsheetId: FULL_LIST_ID, 
      range: ['LIST!A1:B'] 
     }).then((response) => { 
      this.setState({ res: response.result.values }); 
     }, (response) => { 
      throw response.result.error.message; 
     }); 
     } 

    _renderList() { 
     // this uses the values fetched locally  
     // return this.state.res.map((val, index) => {}); 
    } 

render() { 
    if (!this.state.res) { 
     return <div>Loading...</div>; 
    } 
    return (
     <div> 
       {this._renderList()} 
     </div> 
    ); 
    } 
} 


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

export default connect(mapStateToProps, { fetchList })(DropdownList); 

是否有人能幫助我嗎? 謝謝

回答

0

好的,解決了! 這是一個同步問題,所以我需要在我的Action Creator中使用Redux-Thunk作爲中間件。

相關問題