【问题标题】:Dispatching Action inside Fetch在 Fetch 中调度 Action
【发布时间】:2017-03-13 10:42:39
【问题描述】:

我正在使用 fetch 进行异步调用,然后尝试通过根据返回的 json 数据的结果调度操作来设置状态。

我正在使用二维码阅读器读取传递给我的 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});
     }
   }

我正在使用 react-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} Reducers 可能不会派发动作

我的 reducer 都没有调度任何操作,当我将它从 Promise .then() 块中取出时,代码工作正常。

为了完整起见,这里是简单的 getAppointment 获取服务:

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

非常感谢任何帮助。

【问题讨论】:

    标签: react-native ecmascript-6 redux react-redux es6-promise


    【解决方案1】:

    我不确定你的绑定动作的语法是什么,以前没见过。这是我为一个项目编写的代码示例,我在其中执行获取请求,然后将响应设置为状态:

    SearchBar.jsx(这会向 Solr 发出一个 http 请求并返回一个 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;
    }
    

    导出到组合函数(虽然只有一个 reducer atm):

    import {combineReducers} from 'redux';
    import ResponseReducer from './reducer-response';
    
    const allReducers = combineReducers({
        response: ResponseReducer
    });
    
    export default allReducers;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2019-02-01
      • 2018-01-03
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多