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

时间:2018-06-17 06:07:34

标签: redux react-redux

我已经阅读了有关此错误的多个来源,但我无法弄清楚我在这里做错了什么。我已经使用自定义中间件了,我相信我正在正确地返回动作。有什么建议吗?

app.js

import React from "react";
import ReactDOM from "react-dom";
import { renderToString } from "react-dom/server";
import { Provider } from "react-redux";
import { createStore, applyMiddleware, compose } from "redux";
import thunk from 'redux-thunk';

import rootReducer from '../reducers';
import DataProvider from "./DataProvider";
import QuestionContainer from "./QuestionContainer";
import * as actions from "../actions";

const App = () => <QuestionContainer />;
const store = createStore(
    rootReducer,
    applyMiddleware(thunk)),
);

store
    .dispatch(actions.fetchQuestions())
    .then(() => response.send(renderToString(<Provider store={ store }><App /></Provider>)))

然后在actions.js

export function fetchQuestions() {
    return (dispatch) => {
        return fetch('/api/questions')
            .then(response => response.json())
            .then(data => dispatch(loadRequestData(data)),
        )
    }
}

浏览器控制台中显示错误:

redux.js:208 Uncaught (in promise) Error: Actions must be plain objects. Use custom middleware for async actions.
    at dispatch (redux.js:208)
    at eval (index.js:12)
    at dispatch (redux.js:571)
    at eval (actions.js:35)

1 个答案:

答案 0 :(得分:1)

我认为这部分代码存在问题:

store
.dispatch(actions.fetchQuestions())
.then(() => response.send(renderToString(<Provider store={ store }><App /></Provider>)))

当您创建异步调用时,您只想在操作中执行此操作,而不是在reducer / store中执行此操作。

所以你需要删除这一行.then(() => response.send(renderToString(<Provider store={ store }><App /> 而不只是做:

const app = (
        <Provider store={store}>
            <App />
        </Provider>
)

ReactDOM.render(app, document.getElementById('root'));

另外,做一些操作,这将有助于更新reducer中的商店。像这样:

export const fetchBegin = () => ({
    type: 'FETCH_BEGIN'
})

export const fetchSuccess = (payload) => ({
    type: 'FETCH_SUCCESS'
    payload
})

export const fetchQuestions = () => {
    return (dispatch) => {
        dispatch(fetchBegin())
        return fetch('/api/questions')
            .then(response => response.json())
            .then(data => dispatch(fetchSuccess(data))
        )
    }
}

然后在减速器中:

const initialState = {
    call: [],
    loading: false
}

const reducer = (state = initialState, action){
    switch(action.type){
        case 'FETCH_BEGIN:
            return{
            ...state,
            loading: true,
        case 'FETCH_SUCCESS':
            return{
            ...state,
            call: action.payload,
            loading: false,
        }
        default:
            return state
    }
}

这应该适用于imho。

相关问题