2016-10-31 3 views
0

Я делаю асинхронный вызов с использованием fetch, а затем пытаюсь установить состояние, отправив действие на основе результата возвращенных данных json.Dispatching Action in 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}); 
    } 
    } 

Я использую среагировать-Redux, чтобы связать свои действия с моими диспетчерами так:

 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;