Next.js和Redux:getInitialProps不返回属性

gwbalxhn  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(135)

需要一个React专业来帮助我在这里。提前感谢!
我试图找到一个甜蜜点使用redux和NEXT JS,而不使设置过于复杂。

目标:利用getInitialProps(用于SSR)来分派操作(尤其是涉及API请求的操作),以便预加载数据并对数据进行SSR。

为了实现这一点,我做了以下设置:

_应用程序组件

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

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';

// REDUCER
import reducers from '../redux/reducers';

// STORE
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);

登录页面(页面/index. js)

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 = ({ posts }) => {

    console.log('POSTS', posts); // <-- NOT getting posts for some reason via GIPs() !!!

    return <h1>Home page</h1>
}

LandingPage.getInitialProps = async (ctx, { store }) => {
    await store.dispatch(fetchPosts());
    const posts = await store.getState().posts;
    console.log('RETURNING POSTS', posts) // <-- this returns the list of posts
    return { ...posts }
}

export default LandingPage;

操作

// custom axios function
import api from '../../api';

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

问题:事件虽然getInitialProps()是POSTS列表中的控制台日志,但我无法将POSTS从getInitialProps检索到LandingPage组件。当我控制台记录帖子或属性时,它显示未定义。

有没有更好的方法?我错过了什么?

shstlldc

shstlldc1#

getInitialProps返回的对象将被合并到组件的props中。因此,您可能需要删除LandingPageAppComponentgetInitialProps函数中的反结构化操作符:

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 = ({ posts }) => { // <-- destructuring "posts" property from props object

    console.log('POSTS', posts); // <-- posts should be available here

    return <h1>Home page</h1>
}

LandingPage.getInitialProps = async (ctx, { store }) => {
    await store.dispatch(fetchPosts());
    const posts = await store.getState().posts;
    console.log('RETURNING POSTS', posts) // <-- this returns the list of posts
    return { posts }; // <-- return an object with "posts" property
}

export default LandingPage;
kuuvgm7e

kuuvgm7e2#

2022答案(使用TypeScript):

要使用TypeScript + Redux(从App.tsx开始,使其在所有页面上可用)实现此目的,语法应类似于:

MyApp.getInitialProps = customWrapper.getInitialAppProps(
  (store) => async (appContext) => {
    const response = await getAuthInfo();

    if ((response as any)?.error) {
      store.dispatch(setAuthState(null));
    } else {
      store.dispatch(setAuthState(response as TAuthInfo));
    }

    const appProps = await App.getInitialProps(appContext);
    return { ...appProps };
  },
);

export default customWrapper.withRedux(MyApp);

请注意,目前在Next.js中,App目前不支持getStaticPropsgetServerSideProps等Next.js数据提取方法。
customWrapper来自以下配置:https://blog.logrocket.com/use-redux-next-js/

相关问题