首页 > 解决方案 > 如何在 NextJS 中以多步形式传递数据?

问题描述

我最近开始使用 NextJS 和 React。

我正在尝试在我的应用程序中实现多页面表单,但我不知道如何将表单数据从一个页面持久化并传递到另一个页面。

有许多关于使用状态管理库和上下文 API 的指南,但它们都在 reactjs 中或定义了不同组件之间的使用。

我的 _app.js 看起来像这样:

const AppComponent = ({ Component, pageProps, currentUser }) => {
  return (
    <div>
      <AppWrapper>
        <Header currentUser={currentUser} />
        <Component {...pageProps} />
      </AppWrapper>
    </div>
  );
};
AppComponent.getInitialProps = async (appContext) => {
  const client = buildClient(appContext.ctx);

  const { data } = await client.get('/api/client/currentuser');
  let pageProps = {};
  if (appContext.Component.getInitialProps) {
    pageProps = await appContext.Component.getInitialProps(appContext.ctx);
  }
  return {
    pageProps,
    ...data,
  };
};

export default AppComponent

上下文状态.js

import { createContext, useContext } from 'react';

const AppContext = createContext();

export function AppWrapper({ children }) {
  let sharedState = {
    /* whatever you want */
  };

  return (
    <AppContext.Provider value={sharedState}>{children}</AppContext.Provider>
  );
}

export function useAppContext() {
  return useContext(AppContext);
}

现在我需要将表单的数据保存在第 1 页(姓名、姓氏)并将其传递到第 2 页(电子邮件和电话),最后是我想要包含所有字段的摘要。如何从以下页面设置 shared_state?

step1.js 从“反应”导入反应;

function Step1(props) {
  return (
    <div>
      <p>Name: <input name="name" /></p>
      <p>Surname: <input name="surname" /></p>
    </div>
  );
}

export default Step1;

step2.js

import React from "react";

export default function Step2(props) {
  return (
    <div>
      <p>Email: <input name="email" /></p>
      <p>Phone: <input name="Phone" /></p>
    </div>
  );

如何在步骤 1 中从用户数据设置状态并将数据传递到步骤 2。谁能帮我解决这个问题?

标签: reactjsreact-reduxnext.jsstate-management

解决方案


在 React 中工作的所有相关状态都将在 Next.js 中工作,将其_app.js视为父组件,每个页面都是其子组件。

React Context 也可以工作,但如果您想通过大型组件层次结构将状态从父级传递给子级,它会很有用。在这里,您只有您_app.js和 2 个直接孩子,它们是您的 2 个表单页面。

You can simply create a state in _app.js and pass that state as prop to your form pages like this:

import { useState } from "react"

const AppComponent = ({ Component, pageProps, currentUser }) => {
  const [formData, setFormData] = useState({});
  const updateFormData = (newData) => {
    setFormData({ ...formData, ...newData });
  };
  return <Component {...pageProps} updateFormData={updateFormData} />;
};
function Step1({ updateFormData }) {
  const handleNameChange = (event) => {
    updateFormData({ name: event.target.value });
  };
  const handleSurnameChange = (event) => {
    updateFormData({ surname: event.target.value });
  };
  return (
    <div>
      <p>
        Name: <input name="name" onChange={handleNameChange} />
      </p>
      <p>
        Surname: <input name="surname" onChange={handleSurnameChange} />
      </p>
    </div>
  );
}

By doing the same in your second form page, you will have all your form data in the formData variable, which you can pass to another page to display result, do an API call etc.


推荐阅读