简体   繁体   English

NextJS 和 Redux:无法使用 thunk 中间件

[英]NextJS and Redux : Cannot use thunk middleware

I am trying to make use of thunk to make async calls to api, but I am still getting the error: Unhandled Runtime Error: Actions must be plain objects.我正在尝试使用 thunk 对 api 进行异步调用,但我仍然收到错误消息:未处理的运行时错误:操作必须是普通对象。 Use custom middleware for async actions.使用自定义中间件进行异步操作。

This is my custom _app component :这是我的自定义_app 组件

// to connect redux with react 
import { Provider } from 'react-redux';
import { createWrapper } from 'next-redux-wrapper';

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

const store = createStore(reducers, applyMiddleware(thunk));

const AppComponent = ({ Component, pageProps }) => {
    return (
        <Provider store={store}>
            <Component {...pageProps} />
        </Provider>
    )
}

AppComponent.getInitialProps = async (appContext) => {
    let pageProps = {};
    if (appContext.Component.getInitialProps) {
        pageProps = await appContext.Component.getInitialProps(appContext.ctx);
    };
    return { ...pageProps }
}

// returns a new instance of store everytime its called
const makeStore = () => store;
const wrapper = createWrapper(makeStore);

export default wrapper.withRedux(AppComponent);

And this is the landing page where I am dispatching the action creator:这是我派遣动作创建者的登陆页面

import { connect } from 'react-redux';
import { fetchPosts } from '../redux/actions';
import { bindActionCreators } from 'redux';
import { useEffect } from 'react';
import Link from 'next/link';

const LandingPage = (props) => {
    useEffect(() => {
        props.fetchPosts();
    }, [props]);

    return <div>
        <Link href="/">
            <a>Home</a>
        </Link>
    </div>
}

LandingPage.getInitialProps = async ({ store }) => {
    store.dispatch(await fetchPosts());
}

const mapDispatchToProps = (dispatch) => {
    return {
        // so that this can be called directly from client side
        fetchPosts: bindActionCreators(fetchPosts, dispatch)
    }
}


export default connect(null, mapDispatchToProps)(LandingPage);

Action:行动:

import api from '../../api';

// returning a function and dispatching manually to make use of async await to fetch data
export const fetchPosts = async () => async (dispatch) => {
    const response = await api.get('/posts');
    dispatch({
        type: 'FETCH_POSTS',
        payload: response
    });
};

Sadly the GitHub Next + Redux example NEXT+REDUX is really complicated for me to understand as I am trying redux for the first time with NextJS.遗憾的是,GitHub Next + Redux 示例NEXT+REDUX对我来说理解起来真的很复杂,因为我第一次使用 NextJS 尝试 redux。 And every blog post has it's own way of doing it and nothing seems to be working.每篇博文都有自己的做法,但似乎没有任何效果。

I do not want it to make it any more complicated.我不想让它变得更复杂。 I would really appreciate if anyone could help me why I am getting this error?如果有人能帮助我为什么会收到此错误,我将不胜感激?

the problem is not with next.js when you calling this:当您调用此代码时,问题不在于 next.js:

LandingPage.getInitialProps = async ({ store }) => {
    store.dispatch(await fetchPosts());
}

fetchPosts here is a Promise and dispatch dispatch action must be a plain object so to solve this remove async word from it like this:这里的 fetchPosts 是一个 Promise 并且调度调度动作必须是一个普通的 object 所以要解决这个问题,像这样从中删除异步字:

export const fetchPosts = () => async (dispatch) => {
    const response = await api.get('/posts');
    dispatch({
        type: 'FETCH_POSTS',
        payload: response
    });
};

butt if you want to wait for api response instead you need call it in the component like this:如果您想等待 api 响应,则需要在组件中调用它,如下所示:

const App= ()=>{
const dispatch = useDispatch()
useEffect(() => {
 const fetch = async()=>{
try{
    const response = await api.get('/posts');
    dispatch({
        type: 'FETCH_POSTS',
        payload: response
    });
}
catch(error){
throw error
}
 }
 fetch()
    }, []);

return ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM