2016-10-31 32 views
0

我使用fetch進行異步調用,然後嘗試根據返回的json數據的結果分派動作來設置狀態。Fetch中的調度動作

我正在使用QR碼閱讀器讀取傳遞給我的didScan方法的代碼。

didScan(code) { 
     if (this.state.showCamera){ 
     this.props.pushNewRoute('finder'); 
     getAppointment(code) 
     .then((appointment)=>{ 
     if (appointment.valid){ 
      this.props.appointmentDetails(appointment); 
      this.props.resetRoute('summary'); 
     }else{ 
      this.props.resetRoute('error'); 
     } 
     }) 
     .catch((error) => { 
     this.props.resetRoute('error'); 
     }); 
     this.setState({showCamera: false}); 
    } 
    } 

我使用的反應,終極版,以我的行動綁定到我的調度員是這樣的:

 function bindActions(dispatch){ 
     return { 
      resetRoute:(route)=>dispatch(resetRoute(route)), 
      pushNewRoute:(route)=>dispatch(pushNewRoute(route)), 
      appointmentDetails:(details)=>dispatch(appointmentDetails(details)) 
     } 
    } 

    export default connect(null, bindActions)(Scanner); 

但是當承諾被我getAppointment服務返回它時,它試圖做路由失敗。

this.props.resetRoute('summary'); 

的錯誤是

可能未處理的承諾,拒絕{ID:0} 減速可能不會派遣行動

無我減速的調度的任何行動和代碼工作正常時,我將它從Promise.then()塊中取出。

下面是簡單的getAppointment的完整性提取服務:

export function getAppointment(id:string) { 
    return fetch('http://myurl/' + id + '/') 
    .then((response) => response.json()) 
    .catch((error) => { 
    console.error(error); 
    return error; 
    }); 
} 

任何幫助極大的讚賞。

回答

0

我不確定你的語法是綁定的行爲,以前沒有看到過。下面是我的一個項目,我做一個GET請求進行,然後設置響應作爲國家代碼示例:

SearchBar.jsx(這確實一個HTTP請求到Solr並得到一個JSON對象返回,然後集,對象作爲狀態)

import React, {Component} from 'react'; 
import httpClient from 'axios'; 
import {bindActionCreators} from 'redux'; 
import {connect} from 'react-redux'; 
import {setResponse} from '../actions/index' 

class SearchBar extends Component { 

    constructor(props) { 
    super(props); 

    this.search = this.search.bind(this); 
    } 

    search() { 
    let q = document.getElementById('searchbar').value; 
    httpClient(`/search?q=${q}`, { baseURL: window.location.href }) 
     .then(resp => { 
     console.log(resp); 
     this.props.setResponse(resp); 
     }); 
    } 

    render() { 
    return (
     <div> 
     <input type='text' id='searchbar'/> 
     <button onClick={this.search}>Search</button> 
     </div> 
    ); 
    } 
} 

function mapDispatchToProps(dispatch){ 
    return bindActionCreators({setResponse: setResponse}, dispatch); 
} 

export default connect(null, mapDispatchToProps)(SearchBar); 

這是動作:

export const setResponse = (res) => { 
    return { 
     type: 'RESPONSE_RECEIVED', 
     payload: res 
    } 
}; 

這是減速機:

export default function (state = null, action) { 
    switch (action.type) { 
     case 'RESPONSE_RECEIVED': 
      return action.payload; 
      break; 
    } 
    return state; 
} 

哪個導出到組合函數(儘管只有一個減速器大氣壓):

import {combineReducers} from 'redux'; 
import ResponseReducer from './reducer-response'; 

const allReducers = combineReducers({ 
    response: ResponseReducer 
}); 

export default allReducers;