Skip to content

Commit 6e9d23b

Browse files
committed
Improve redux wrapper
1 parent c9e11b6 commit 6e9d23b

File tree

3 files changed

+34
-9
lines changed

3 files changed

+34
-9
lines changed

next-practise/pages/_app.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@ import reduxWrapper from "../utils/reduxWrapper";
33

44
function MyApp(props) {
55
const { Component, pageProps } = props;
6-
return <Component {...pageProps} />;
6+
console.log({ pageProps });
7+
return <Component {...props} {...pageProps} />;
78
}
89

10+
MyApp.getInitialProps = () => {
11+
return { testProp: "A props" };
12+
};
13+
914
export default reduxWrapper.wrapper(MyApp);

next-practise/pages/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { useSelector } from "react-redux";
44
import styles from "../styles/Home.module.css";
55

66
export default function Home(props) {
7-
const count = useSelector((state) => state.counter);
7+
const count = useSelector((state) => state.count);
88

99
console.log({ count });
1010

next-practise/utils/reduxWrapper.js

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,44 @@ function rootReducer(state = initialState, action) {
1313
return state;
1414
}
1515
}
16+
const getIsServer = () => typeof window == "undefined";
1617

17-
const initializeStore = (preloadedState = {}) =>
18-
createStore(rootReducer, preloadedState);
18+
const initializeStore = (preloadedState = {}) => createStore(rootReducer);
1919

2020
function wrapper(Component) {
21-
// function WithRedux(appProps) {
22-
// const store = useRef(initializeStore());
23-
// return (
24-
// );
25-
// }
21+
const displayName = `withRedux(${
22+
Component.displayName || Component.name || "Component"
23+
})`;
24+
25+
const hasInitialProps = "getInitialProps" in Component;
26+
27+
console.log({ displayName, hasInitialProps });
2628

2729
class WithRedux extends App {
2830
constructor(props) {
2931
super(props);
3032
this.reduxStore = initializeStore();
3133
}
3234

35+
static getInitialProps(ctx) {
36+
console.log(ctx);
37+
38+
return {};
39+
}
40+
3341
render() {
42+
console.log(this.props);
43+
44+
const { initialState, initialProps, ...props } = this.props;
45+
46+
console.log({ initialProps, initialState });
47+
48+
let finalProps = {};
49+
50+
finalProps.pageProps = {
51+
initialState: this.reduxStore.getState(),
52+
};
53+
3454
return (
3555
<Provider store={this.reduxStore}>
3656
<Component {...this.props} />;

0 commit comments

Comments
 (0)