简体   繁体   中英

Nextjs redux, thunk and getInitialProps - how to implement

I want to use nextjs in my new project with redux and thunk also. I wondering how to implement all packages correctly.

In my previous projects pages has HOC components like:

import {connect} from 'react-redux';
import Page from './about';
import {fetchUsers} from '../../actions/user';

const mapStateToProps = (state) => {
    const {users} = state;
    return users;
};

const mapDispatchToProps = (dispatch) => {
    return {
        fetchUsers: () => dispatch(fetchUsers())
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Page);

And method to fetch users I implemented in componentDidMount

How to implement the same logic for nexjs ?

What have I do?

  1. Implemented store (base on next-redux-wrapper in _app.js)
  2. Created HOC component (like below) with mapStateToProps and mapDispatchToProps

Currently I thinking about use somehow this.props.fetchUsers method into getInitialProps - documentation say that this method should be used to fetch data before render site.

Please help me with correctly redux implementation for nextjs

You can follow this example The correct way is to pass the store to the getInitialProps context and to the App component so you can pass it to the Provider .

The getInitialProps can't access to instance of the component, this is not accessible, so you can't call this.props.fetchUsers , but, because you are passing store to its context, you can do store.dispatch(fetchUsers()) and remove dispatch from mapDispatchToProps .

Generally I dispatch actions in getInitialProps and then map state to props within connect .

@gg_

Your solution works but only when I change page using Link If I refresh/reload page await store.dispatch(fetchUsers()); doesn't trigger.

What is the way to do this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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