如何使用withRedux(pageName)在nextjs中获取和获取数据

时间:2019-10-23 06:43:53

标签: reactjs redux next.js redux-thunk server-side-rendering

我是nextjs和ssr的新手。

我想通过分派我的动作从getInitialProps获取数据,并在Index页面中将这些数据作为props获取。但是index props为null,我也想使用mapstatetoprops获取state和props。我可以同时做这两个吗? 另一个问题是applymiddleware中的重击是错误的!!

![截图nextjs代码] [1]

我正在使用json-server。我在https://github.com/zeit/next.js/blob/canary/examples/with-redux/store.js配置存储文件,例如nexjs示例

我在单独的目录中有actiona和reducer,并将它们导入以存储文件。

store.js

import { createStore, applyMiddleware } from 'redux'
import thunk from "redux-thunk";
import { composeWithDevTools } from 'redux-devtools-extension'
import reducers from '../client/redux/reducers'
const initialState = {};


export const initializeStore = (preloadedState = initialState) => {
    return createStore(
        reducers,
        preloadedState,
        composeWithDevTools(applyMiddleware(thunk))
    )
}

减速器组合:

 import {combineReducers} from "redux";
    import authReducer from './authReducer';
    import postReducer from "./postReducer";
    import userReducer from "./userReducer";
    import {reducer as fromReduce} from "redux-form";

    const rootReducer = combineReducers({
        auth: authReducer,
        posts: postReducer,
        form: fromReduce,
        user:userReducer
    });
    export default rootReducer;

这是我的动作:

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

index.js

 import React from "react";
    import {withRedux} from '../lib/redux'
    import {connect} from 'react-redux';
    import Header from "../components/header";
    import {fetchPosts} from "../redux/actions/postAction";

    import PostList from '../components/postList'

    const Index = (props) => {
        console.log(props)

        return (
            <React.Fragment>
                <Header/>
                <PostList posts={props.posts}/>
            </React.Fragment>

        );
    };
    Index.getInitialProps = async ({reduxStore}) => {
        const {dispatch} = reduxStore;
        await dispatch(fetchPosts());
        return {}
    }


    export default withRedux(Index);

console.log(props)返回

 url:
   { query: [Getter],
     pathname: [Getter],
     asPath: [Getter],
     back: [Function: back],
     push: [Function: push],
     pushTo: [Function: pushTo],
     replace: [Function: replace],
     replaceTo: [Function: replaceTo] } }

我怎么了?为什么帖子没有显示在控制台中?

0 个答案:

没有答案