gpt4 book ai didi

javascript - 将 react redux 与 next.js 结合使用

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:31 25 4
gpt4 key购买 nike

我尝试将 Redux 与 next.js starter 结合使用项目,我在项目上安装了 next-redux-wrapper 但我不确定这个项目的根文件在哪里。

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

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

问候。

最佳答案

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

虽然这个演示是针对 next.js 的,但它应该适用于 nextjs-starter。

安装 next-redux-wrapper:

npm install --save next-redux-wrapper

添加_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);

然后,可以简单地连接实际的页面组件:这个演示如何在页面中连接 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);

有关详细信息,请参阅文档:next-redux-wrapper

关于javascript - 将 react redux 与 next.js 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com