Redux Thunk:动作必须是普通对象

时间:2017-10-11 17:18:48

标签: react-native redux redux-thunk

我按照这些two guides在Action with Redux Thunk中实现了API调用:

configureStore.js

import { createStore, applyMiddleware } from 'redux'
import rootReducer from '../core/reducers'
import thunk from 'redux-thunk'

export default function configureStore() {
    let store = createStore(
        rootReducer,
        applyMiddleware(thunk)
    );

    return store
}

我的行动,product.js

function increment() {
    return {
        type: FETCHING_DATA
    };
}

export function fetchData() {
    return dispatch => {
        setTimeout(() => {
            // Yay! Can invoke sync or async actions with `dispatch`
            dispatch(increment());
        }, 1000);
    };
}

来自Product.js屏幕的电话:

class Product extends Component {

    constructor(props: Props) {
        super(props);

        this.state = {products: null};
    }

    componentDidMount() {
        this.props.fetchData();
    };

    // Other code
}

function mapStateToProps (state) {
    return {
        cart: state.cart,
        product: state.product
    }
}

function mapDispatchToProps (dispatch) {
    return {
        plusOneProduct: (id) => dispatch(plusOneProduct(id)),
        clearCart: () => dispatch(clearCart()),
        fetchData: () => dispatch(fetchData())
    }
}

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

app.js文件:

import {View} from 'react-native';
import React from 'react';
import {NativeRouter, Route, Redirect} from 'react-router-native';

import {Root} from './config/router';
import configureStore from './configureStore'

const store = configureStore();

const MyApp = () => {
    return (
        <Root store={store}/>
    );
};

export default MyApp;

我确实完全按照这两篇文章的说法和官方文档,但在产品页面登陆时出现此错误:

  

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

似乎我的React Thunk中间件没有应用。我怎么检查这个?

1 个答案:

答案 0 :(得分:1)

正如评论部分所述,问题在于您忘记将Provider组件包装到顶级组件中。因此,要解决此问题,您应该使用Provider组件包装Root并将存储传递到那里。

//... rest of imports
import { Provider } from 'react-redux';

const store = configureStore();

const MyApp = () => {
    return (
      <Provider store={store}>
        <Root/>
      </Provider>
    );
};