首页 > 解决方案 > 如何在nextjs(通过reactjs)多个页面和组件中共享公共数据?

问题描述

我开发了一个示例应用程序,它是一个非常简单的应用程序,并在 nextjs (reactjs) 中开发。我在 nextjs 中开发的第一个问题是在多个页面和组件之间共享公共数据。我正在使用 useContext 挂钩在不同的页面和组件上共享公共数据,但是当我在其他一些组件/页面中使用此挂钩时出现错误。

以下是我自己的上下文来源:

=====================================================sharedcontext.js========================   
import { createContext, useContext, useState } from "react";
import { getTeams, getLocations } from "../../pages/api/data";

// Create Context object.
const SharedContext = createContext();

// Export Provider.
export function SharedProvider({ children }) {
    const [teams, setTeams] = useState([]);
    const [branches, setBranches] = useState([]);
    const getTeamsData = async (text) => {
        const res = getTeams();
        setTeams(res);
    };
    const getLocationsData = async (text) => {
        const res = getLocations();
        setBranches(res);
    };
    // const { value, children } = props;
    const store = {
        teams,
        branches,
    };
    return <SharedContext.Provider value={store}>{children}</SharedContext.Provider>;
}
// Export useContext Hook.
export function useSharedContext() {
    return useContext(SharedContext);
}

====================================================layout.js===============================    
import React, { useState, useContext } from "react";    
export default function Layout(props) {
    debugger;
    return (
        <>               
            <main role="main">
                {props.preContainer && props.preContainer}
                <div className="album py-5 bg-light">
                    <div>{props.children}</div>
                </div>
            </main>
            <Footer />
        </>
    );
}

==================================================index.js===========================
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.scss";    
import Layout from "../layout/layout";
const CURRENCIES = {
    Euro: {
        symbol: "€&quot;,
        label: "Euro",
    },
    Usd: {
        symbol: "$",
        label: "US Dollar",
    },
};

export default function Home(initialData) {
    return (
        <div>
            <Head>
                <title>test</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <Layout></Layout>
        </div>
    );
}
==========================================_app.js==============================
import "bootstrap/dist/css/bootstrap.min.css";
function MyApp({ Component, pageProps }) {
    return <Component {...pageProps} />;
}

export default MyApp;

==================================showroomsection.js=====================
import React from "react";
import { Row, Col, Container } from "react-bootstrap";
import TextBox from "./TextBox";

export default function ShowroomSection(props) {
    return (
        <div className="p-4">
            <div className="ic_showrooms">
                <h3>Our Showrooms</h3>
                <Row>
                    {props.locationDetails.map((location, index) => (
                        <Col lg={4} key={index}>
                            <TextBox title={location.name} classes={location.name.toLowerCase()} linkText="Book an Appointment" linkSrc={`/showrooms/${location.name}`} text={location.address} phone={location.phone} />
                        </Col>
                    ))}
                </Row>
            </div>
        </div>
    );
}



=========================================about.js==============================
import React, { useState, useEffect } from "react";
import { Container } from "react-bootstrap";
import Layout from "../layout";
import Head from "next/head";
import { SharedProvider, useSharedContext } from "../contexts/sharedcontext";    
//initialData
export default function About(initialData) {
   
    debugger;
    const contextData = useSharedContext();
    return (
        <Layout>
            <div>
                <Container fluid>                      
                   <ShowroomSection locationDetails={contextData.branches} />
                 </Container>
            </div>
        </Layout>   
       )  
  }
=====================================package.json============================
{
    "name": "test",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint",
        "export": "npm run build && next export -o _static"
    },
    "dependencies": {
        "bootstrap": "^5.0.2",
        "next": "11.0.1",
        "node-sass": "^4.14.1",
        "react": "17.0.2",
        "react-bootstrap": "^1.6.1",
        "react-dom": "17.0.2",
        "react-icons": "^4.2.0"
    },
    "devDependencies": {
        "eslint": "7.29.0",
        "eslint-config-next": "11.0.1"
    }
}

尝试运行应用程序开发模式时出现以下错误。

Server Error

TypeError:无法读取未定义的属性“分支”

生成页面时发生此错误。任何控制台日志都将显示在终端窗口中。源代码 build\server\pages\about.js (60:55) @ About

58 | 59 |

60 | | ^ 61 | 62 | 63 |

我试图修复它,但无济于事。其中有什么问题?

标签: reactjsnext.js

解决方案


推荐阅读