简体   繁体   English

nextjs redux,thunk和getInitialProps - 如何实现

[英]Nextjs redux, thunk and getInitialProps - how to implement

I want to use nextjs in my new project with redux and thunk also. 我想在我的新项目中使用nextjs还有reduxthunk I wondering how to implement all packages correctly. 我想知道如何正确实现所有包。

In my previous projects pages has HOC components like: 在我之前的项目页面中有HOC组件,如:

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 以及获取我在componentDidMount实现的用户的方法

How to implement the same logic for nexjs ? 如何为nexjs实现相同的逻辑?

What have I do? 我做了什么?

  1. Implemented store (base on next-redux-wrapper in _app.js) 实现商店(基于_app.js中的next-redux-wrapper)
  2. Created HOC component (like below) with mapStateToProps and mapDispatchToProps 使用mapStateToPropsmapDispatchToProps创建HOC组件(如下所示)

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. 目前我正在考虑以某种方式使用this.props.fetchUsers方法进入getInitialProps - 文档说这个方法应该用于在渲染站点之前获取数据。

Please help me with correctly redux implementation for nextjs 请帮我正确地为nextjs实现redux实现

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 . 您可以按照此示例正确的方法是将存储传递给getInitialProps上下文和App组件,以便将其传递给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 . getInitialProps无法访问组件的实例,这是不可访问的,所以你不能调用this.props.fetchUsers ,但是,因为你将商店传递给它的上下文,你可以做store.dispatch(fetchUsers())并从mapDispatchToProps删除调度。

Generally I dispatch actions in getInitialProps and then map state to props within connect . 通常我会在getInitialProps调度动作,然后将状态映射到connect props。

@gg_ @gg_

Your solution works but only when I change page using Link If I refresh/reload page await store.dispatch(fetchUsers()); 您的解决方案有效但仅当我使用链接更改页面时如果我刷新/重新加载页面await store.dispatch(fetchUsers()); doesn't trigger. 不会触发。

What is the way to do this? 这样做的方法是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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