返回

reactjs-无法使用 next-redux-wrapper 让 Redux (Thunks) 与 NextJS 一起工作:未调用 getInitalProps

发布时间:2022-03-08 11:30:30 280
# 前端# html5# node.js

我正在尝试让Redux使用next Redux包装器与thunks一起工作。我看过示例代码,但我的代码不起作用。我走来走去,再也见不到森林了。目前我的“getInitialProps”在索引中。js没有被调用,因此我的数据从未被加载,因为我从未调度数据加载操作。商店已创建,但它是空的。

// _app.js
import {createStore} from "redux";
import {Provider} from "react-redux";
import App from "next/app";
import withRedux from "next-redux-wrapper";
import initStore from '../redux/store'
function MyApp({ Component, pageProps,store }) {
    console.log('in _app', store.getState())
    return (
        
            
        
    );
}
export default withRedux(initStore,{debug:true})(MyApp);



// store.js
import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './root-reducer'
const store = () => configureStore({
    reducer: rootReducer,
})
export default store



// index.js
import React from 'react'
import Head from 'next/head'
import Nav from '../components/nav'
import {useDispatch} from "react-redux"
import {fetchPosts} from '../redux/posts'
const Home = () => {
 return  (
Home
) } Home.getInitialProps = async ({store,isServer}) => { console.log('about to dispatch') store.dispatch(fetchPosts()) return {store,isServer} } export default Home

编辑

这奏效了。我想它必须是一门课,尽管实例在NextJS网站上使用了一个功能组件

import App from 'next/app'
import React from 'react'
import withRedux from "next-redux-wrapper";
import {Provider} from 'react-redux'
import initStore from '../redux/store'

const makeStore = (initialState, options) => {
    return initStore(initialState)
};
class MyApp extends App {

static async getInitialProps({Component, ctx}) {


        const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};

        return {pageProps};

    }

    render() {
        // @ts-ignore
      const {Component, pageProps, store} = this.props;
        return (
          
              
          
        );
    }

}

export default withRedux(makeStore)(MyApp);
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像