Redux-Observable与Axios结合使用时的问题

时间:2019-01-09 23:02:32

标签: reactjs redux redux-observable

我正在尝试学习redux-observable,但在让我的应用返回数据时似乎遇到了问题。我一直在下面看到错误,我不确定我要去哪里或该错误实际上意味着什么。

错误:TypeError:axios__WEBPACK_IMPORTED_MODULE_3 ___ default.a.get(...)。map不是函数

动作:

import { FETCH_DATA, FETCH_DATA_FAIL } from './constants';

export const fetchData = exampleData => ({
type: FETCH_DATA,
payload: { exampleData }
});

export const fetchDataFail = () => ({
type: FETCH_DATA_FAIL
});

EPIC:

 import 'rxjs';
 import { FETCH_DATA, FETCH_DATA_FAIL } from './constants';
 import { fetchData  } from './actions';
 import axios from 'axios';
 import { Observable } from 'rxjs';
 import { mergeMap } from 'rxjs/operators';
 import { ofType } from 'redux-observable';

 export const exampleEpic = action$ =>
   action$.pipe(ofType(FETCH_DATA),
   mergeMap(action =>
     axios.get('https://jsonplaceholder.typicode.com/todos/1')
       .map(response => fetchData(response))
       .catch(error => Observable.ofType(FETCH_DATA_FAIL)))
);

减速机:

     import { FETCH_DATA, FETCH_DATA_FAIL } from './constants';
     import { combineReducers } from 'redux';

     const initialState = {};

     export const exampleData = (state = initialState, action) => {
       switch (action.type) {
         case FETCH_DATA:
           return action.payload
         case FETCH_DATA_FAIL:
           return {};
         default:
           return state;
       }
     };

     export default combineReducers({
       exampleData
     });

示例组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchData } from './actions';

class App extends Component {

  onClick = ()=>{
    this.props.fetchData();
  }

  render() {
    return (
      <div>
        <button onClick={this.onClick}><h1>Hello World</h1></button>
        {JSON.stringify(this.props.data) }
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    data: state
  }
};

function mapDispatchToProps(dispatch) {
  return {
    fetchData: () => dispatch(fetchData())
  }
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

1 个答案:

答案 0 :(得分:3)

使用.then可以解决问题,正确的方法是使用rxjs的from函数,如下所示

 import 'rxjs';
 import { FETCH_DATA, FETCH_DATA_FAIL } from './constants';
 import { fetchData  } from './actions';
 import axios from 'axios';
 import { Observable, from } from 'rxjs';
 import { mergeMap, map } from 'rxjs/operators';
 import { ofType } from 'redux-observable';

 export const exampleEpic = action$ =>
   action$.pipe(ofType(FETCH_DATA),
   mergeMap(action =>
     from(axios.get('https://jsonplaceholder.typicode.com/todos/1'))
       .map(response => fetchData(response))
       .catch(error => Observable.ofType(FETCH_DATA_FAIL)))
);

还要确保从rxjs导入.map运算符