我正在尝试使用next-redux-wrapper使Redux与thunk一起使用。我看过示例代码,但是我的代码不起作用。我来回走了,再也看不到树林里的树木了。目前,我的index.js中的“ getInitialProps”没有被调用,因此我的数据从未被加载,因为我从未调度数据加载动作。商店已创建,但是它是空的。
任何帮助,不胜感激!真令人沮丧...
// _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 (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
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 (<div>
<Head>
<title>Home</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Nav />
<div className="hero">
<h1 className="title">Welcome YAA!</h1>
</div>
</div>)
}
Home.getInitialProps = async ({store,isServer}) => {
console.log('about to dispatch')
store.dispatch(fetchPosts())
return {store,isServer}
}
export default Home
编辑:
这有效。我想它必须是一个类,尽管NextJS网站上的example使用了功能组件
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 (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
}
export default withRedux(makeStore)(MyApp);
答案 0 :(得分:3)
我遇到了与您相同的问题,在阅读了此处的评论以及您对问题的解决方案后,我重新编写了我作为功能性组件的内容,它可以正常工作,因此,如果您想使用或针对有相同问题的任何人,这里是解决方案:
import { Provider } from "react-redux";
import withRedux from "next-redux-wrapper";
import { initStore } from "../store/store";
import "./styles.scss";
const MyApp = props => {
const { Component, pageProps, store } = props;
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
};
MyApp.getInitialProps = async ({ Component, ctx }) => {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
return { pageProps };
};
export default withRedux(initStore)(MyApp);