我正在尝试学习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);
答案 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
运算符