javascript 在 next.js 中使用 react redux

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52095681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:49:41  来源:igfitidea点击:

Using react redux with next.js

javascriptreactjsreduxnext.js

提问by Giffary

I try to use Redux with next.js starterproject and I installed next-redux-wrapperon to the project but I'm not sure where is the root file in this project.

我尝试将 Redux 与next.js 入门项目一起使用,并安装next-redux-wrapper到该项目中,但我不确定该项目中的根文件在哪里。

I try to follow the tutorial which shown on the next-redux-wrapperbut no success. Nothing change.

我尝试按照next-redux-wrapper上显示的教程进行操作,但没有成功。没变化。

Please help me how to add Redux on to the project.

请帮助我如何将 Redux 添加到项目中。

Regards.

问候。

回答by yotke

Next.js uses the App component to initialize pages. You can override it and control the page initialization.

Next.js 使用 App 组件来初始化页面。您可以覆盖它并控制页面初始化。

Although this demo is for next.js it should work for nextjs-starter.

尽管此演示适用于 next.js,但它应该适用于 nextjs-starter。

install next-redux-wrapper:

安装 next-redux-wrapper:

npm install --save next-redux-wrapper

npm install --save next-redux-wrapper

Add _app.jsfile to ./pagesdirectory:

_app.js文件添加到./pages目录:

// pages/_app.js
import React from "react";
import {createStore} from "redux";
import {Provider} from "react-redux";
import App, {Container} from "next/app";
import withRedux from "next-redux-wrapper";

const reducer = (state = {foo: ''}, action) => {
    switch (action.type) {
        case 'FOO':
            return {...state, foo: action.payload};
        default:
            return state
    }
};

/**
* @param {object} initialState
* @param {boolean} options.isServer indicates whether it is a server side or client side
* @param {Request} options.req NodeJS Request object (not set when client applies initialState from server)
* @param {Request} options.res NodeJS Request object (not set when client applies initialState from server)
* @param {boolean} options.debug User-defined debug mode param
* @param {string} options.storeKey This key will be used to preserve store in global namespace for safe HMR 
*/
const makeStore = (initialState, options) => {
    return createStore(reducer, initialState);
};

class MyApp extends App {

    static async getInitialProps({Component, ctx}) {

        // we can dispatch from here too
        ctx.store.dispatch({type: 'FOO', payload: 'foo'});

        const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};

        return {pageProps};

    }

    render() {
        const {Component, pageProps, store} = this.props;
        return (
            <Container>
                <Provider store={store}>
                    <Component {...pageProps} />
                </Provider>
            </Container>
        );
    }

}

export default withRedux(makeStore)(MyApp);

And then, actual page components can be simply connected:This demo how to connect index.jsin pages.

然后,可以简单地连接实际的页面组件:这个演示如何index.js在页面中连接。

import Link from "next/link";
import React from "react";
import {
  Container,
  Row,
  Col,
  Button,
  Jumbotron,
  ListGroup,
  ListGroupItem
} from "reactstrap";
import Page from "../components/page";
import Layout from "../components/layout";

import { connect } from "react-redux";

class Default extends Page {
  static getInitialProps({ store, isServer, pathname, query }) {
    store.dispatch({ type: "FOO", payload: "foo" }); // component will be able to read from store's state when rendered
    return { custom: "custom" }; // you can pass some custom props to component from here
  }
  render() {
    return (
      <Layout>content...</Layout>
    );
  }
}

export default connect()(Default);

Refer to the documentation for more information: next-redux-wrapper

更多信息请参考文档:next-redux-wrapper