[英]Nextjs redux, thunk and getInitialProps - how to implement
I want to use nextjs
in my new project with redux
and thunk
also. 我想在我的新项目中使用
nextjs
还有redux
和thunk
。 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? 我做了什么?
HOC
component (like below) with mapStateToProps
and mapDispatchToProps
mapStateToProps
和mapDispatchToProps
创建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.