错误:操作必须是普通对象。使用自定义中间件进行异步操作。在React Native中

时间:2017-10-15 19:00:47

标签: reactjs react-native redux react-redux redux-thunk

每当我尝试发送动作时,我都会收到此错误:

  

错误:操作必须是普通对象。使用自定义中间件进行异步   动作。

我已安装redux-thunk并且没有异步操作,它正在运行。

存储配置:

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { composeWithDevTools } from 'redux-devtools-extension';

import reducers from '../reducers/index';

const logger = createLogger();

export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)));

UI:

...
import { connect } from 'react-redux';
import { getCities } from '../../actions/cities';
...
componentDidMount = async () => {
    try {
      const cities = await this.props.getCities();
      console.log(cities);
    } catch (error) {
      console.log(`errorhome: ${error}`);
    }
    SplashScreen.hide();
  }
...

const mapDispatchToProps = dispatch => ({
  changeNetworkStatus: () => dispatch(changeNetworkStatus),
  getCities: () => dispatch(getCities),
});

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

动作:

import database from '../config/utils';

export const GET_CITIES_START = 'GET_CITIES_START';
export const GET_CITIES_FINISHED = 'GET_CITIES_FINISHED';
export const GET_CITIES_ERROR = 'GET_CITIES_ERROR';

const getCititesStart = () => ({ type: GET_CITIES_START });
const getCititesFinished = cities => ({ type: GET_CITIES_FINISHED, cities });
const getCititesError = error => ({ type: GET_CITIES_ERROR, error });

export const getCitites = () => async (dispatch) => {
  dispatch(getCititesStart());
  try {
    const cities = [];
    const snap = await database.ref('cities').once('value');
    console.log('snap: ', snap);
    snap.forEach((element) => {
      const city = {
        city: element.key,
        coordinate: element.val().coordinate,
      };
      cities.push(city);
    });
    dispatch(getCititesFinished(cities));
  } catch (error) {
    dispatch(getCititesError(error));
  }
};

编辑:如果我也将logger添加到中间件,则会出现以下错误消息:

  

TypeError:无法读取属性'键入'未定义的

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

动作是返回带有动作数据的对象的函数,该数据是具有type属性的对象。

你这样的调度行动:

dispatch(getCities)

你应该派出这样的行动:

dispatch(getCities())