如何从nextjs客户端组件向服务器组件发送表单数据

问题描述 投票:0回答:1

我有一个 bookingForm.tsx 客户端组件,它使用 useEffect 从 json 文件获取数据并在下拉列表中使用它。 bookingform.tsx 也包含在 page.tsx 中。现在我想将表单数据发送到动态路由 [...slug] process.tsx 中的另一个组件。

我尝试使用 useRouter() 但它不接受查询作为参数。 (我是nextjs的初学者)

"use client"
import React, { useState, useEffect } from 'react';
import Select from 'react-select';
// import router from 'next/router';
 import { useRouter } from 'next/navigation';

interface ZRoutes {
  From: string;
  To: string;
  shuttle: number;
  sedan: number;
  van: number;
  minibus: number;
  coach: number;
}

export default function BookingBox() {

 const router = useRouter();
  

  const [pickup, setPickup] = useState<any>(null);
  const [pickupdate, setPickupdate] = useState("");
  const [passengers, setPassengers] = useState("");
  const [dropoff, setDropoff] = useState<any>(null);
  const [myroutes, setMyRoutes] = useState<ZRoutes[]>([]);

  const handleSelectedPickup = (pickup: any) => {
    setPickup(pickup);
  };

  const handleSelectedDropoff = (dropoff: any) => {
    setDropoff(dropoff);
  };

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch('/zanzibar-airport-rates.json');
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        const data = await response.json();
        setMyRoutes(data);
      } catch (error) {
        console.error(error);
      }
    }

    fetchData();
  }, []);

  const myRouteOptions = myroutes.map((route) => ({
    value: route?.To || '',
    label: route?.To || '',
  }));

 

  const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const formData = {
      pickup: pickup?.value || "",
      dropoff: dropoff?.value || "",
      passengers: passengers,
      pickupdate: pickupdate,
    };

    const formattedPickup = pickup?.value.replace(/%20|\s/g, '-');
    const formattedDropoff = dropoff?.value.replace(/%20|\s/g, '-');

     

 router.push({
       pathname: '/${formattedPickup}/${formattedDropoff}`',
       query:formData
    });


  };

  return (
    <div className="booking-area">
      <div className="container">
        <div className="booking-form">
          <h4 className="booking-title">Book Your Airport Taxi</h4>
          <form onSubmit={handleFormSubmit}>
            <div className="row">
              <div className="col-lg-3">
                <div className="form-group">
                  <label>From</label>
                  <Select
                    options={myRouteOptions}
                    value={pickup}
                    onChange={handleSelectedPickup}
                  />
                  <i className="far fa-location-dot" />
                </div>
              </div>

              <div className="col-lg-3">
                <div className="form-group">
                  <label>To</label>
                  <Select
                    options={myRouteOptions}
                    value={dropoff}
                    onChange={handleSelectedDropoff}
                  />
                  <i className="far fa-location-dot" />
                </div>
              </div>

              <div className="col-lg-2">
                <div className="form-group">
                  <label>Passengers</label>
                  <input
                    type="number"
                    className="form-control"
                    placeholder="Passengers"
                    name="Passengers"
                    value={passengers}
                    onChange={(e) => setPassengers(e.target.value)}
                  />
                  <i className="far fa-user-tie" />
                </div>
              </div>

              <div className="col-lg-2">
                <div className="form-group">
                  <label>Pick Up Date</label>
                  <input
                    type="date"
                    name="Pickupdate"
                    className="form-control"
                    placeholder="MM/DD/YY"
                    value={pickupdate}
                    onChange={(e) => setPickupdate(e.target.value)}
                  />
                </div>
              </div>

              <div className="col-lg-2 align-self-end">
                <button className="theme-btn" name="booktaxibtn" type="submit">
                  Book Taxi
                  <i className="fas fa-arrow-right" />
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
next.js13
1个回答
0
投票

要解决此问题,请正确使用模板文字,并使用反引号 (``) 而不是单引号 ('') 形成 URL,以实现正确的字符串插值。

更新您的代码:

 router.push({
        pathname: `/${formattedPickup}/${formattedDropoff}`,
        query: formData,
      });
© www.soinside.com 2019 - 2024. All rights reserved.