【问题标题】:Error: Actions must be plain objects. Use custom middleware for async actions. in React Native错误:操作必须是普通对象。使用自定义中间件进行异步操作。在 React Native 中
【发布时间】:2018-03-27 07:08:58
【问题描述】:

每次我尝试调度我的操作时都会收到此错误:

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

我已经安装了 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)));

用户界面:

...
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: 无法读取未定义的属性“类型”

感谢您的帮助!

【问题讨论】:

  • 对于其他人在这里结束。确保您的函数中没有多余的asyncs。这导致我在标题中收到错误消息。如果函数中没有await,则其标题中应该没有async

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


【解决方案1】:

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

您正在发送这样的操作:

dispatch(getCities)

您应该像这样发送操作:

dispatch(getCities())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 2021-11-04
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多