nextjs配合redux笔记

具体可查看github 上官方提供的 demo
下面对代码关键地方做说明,主要讲解如何实现数据共享。

with-redux-store 的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import React from "react";
import { initializeStore } from "../store";

const isServer = typeof window === "undefined";
const __NEXT_REDUX_STORE__ = "__NEXT_REDUX_STORE__";

function getOrCreateStore(initialState) {
// Always make a new store if server, otherwise state is shared between requests
if (isServer) {
return initializeStore(initialState);
}

// Create store if unavailable on the client and set it on the window object
if (!window[__NEXT_REDUX_STORE__]) {
window[__NEXT_REDUX_STORE__] = initializeStore(initialState);
}
return window[__NEXT_REDUX_STORE__];
}

export default App => {
return class AppWithRedux extends React.Component {
static async getInitialProps(appContext) {
// 在这可以把一些服务端请求数据对state进行初始化,如果没有就用下面注释掉的默认方式
if (isServer) {
const { req } = appContext.ctx;
const session = req.session;
// 根据放到session中的用户数据初始化state
if (session && session.userInfo) {
reduxStore = getOrCreateStore({ user: session.userInfo });
} else {
reduxStore = getOrCreateStore();
}
} else {
reduxStore = getOrCreateStore();
}

// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
//const reduxStore = getOrCreateStore()

// Provide the store to getInitialProps of pages
appContext.ctx.reduxStore = reduxStore;

let appProps = {};
if (typeof App.getInitialProps === "function") {
appProps = await App.getInitialProps(appContext);
}

return {
...appProps,
initialReduxState: reduxStore.getState(), //获取服务端store中的state,传递给前端的store
};
}

constructor(props) {
super(props);
// 创建前端的store实例,前端绑定store时必须使用这个实例,不然新创建的store实例肯定获取不到这个实例的内容,也就会造成state有值,但是就是拿不到
this.reduxStore = getOrCreateStore(props.initialReduxState);
}

render() {
return <App {...this.props} reduxStore={this.reduxStore} />;
}
};
};

在_app.js 中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import App from "next/app";
import React from "react";
import withReduxStore from "../lib/with-redux-store";
import { Provider } from "react-redux";

class MyApp extends App {
render() {
// 注意,这传给store的对象一定是里面返回的reduxStore这个,不能再重新获取一个
const { Component, pageProps, reduxStore } = this.props;
return (
<Provider store={reduxStore}>
<Component {...pageProps} />
</Provider>
);
}
}

export default withReduxStore(MyApp);
文章作者: wenmu
文章链接: http://blog.wangpengpeng.site/2020/01/09/nextjs%E9%85%8D%E5%90%88redux%E7%AC%94%E8%AE%B0/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 温木的博客
微信打赏