• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 React 게시판 컴포넌트간 데이터 전송

컴포넌트간 데이터 전송

7 글 보임 - 1 에서 7 까지 (총 7 중에서)
  • 글쓴이
  • #78677

    이창민
    참가자
    쎈세 contact이라는 컴포넌트에서 입력한 form데이터를 sendForm이라는 컴포넌트에서 출력하려합니다
    근데 contact폼에서 입력한데이터가 서버로전달도 잘 되고 db에 저장도 잘 되는데
    왜 전송 후 sendRequest경로로 이동까지 잘 된 후 빈페이지만 나오는 건가요 ㅠㅠ
    (사용자가 form입력 후 전송을 누르면 sendRequest에서 방금 본인이 전송한 데이터를 확인하는 페이지)
    
    
    
    
     
     
    
    
    import { useNavigate } from "react-router-dom";
    function Contact({ planName }) {
      const navigate = useNavigate();
    // 페이지 이동
          navigate("/sendRequest", {
            state: {
              plan: data.plan,
              location: data.location,
              company: data.company,
              name: data.name,
              phone: data.phone,
              mail: data.mail,
              personnel: data.personnel,
              budget: data.budget,
            },
          });
        } catch (error) {
          console.error(error);
          alert("오류가 발생했습니다.");
        }
      };
    
    
    
    
    
    
    import { useLocation } from "react-router-dom";
    function SendRequest() {
      const location = useLocation();
      const state = location.state;
     
                 

    •               <div>                 <span className="sendRequest-form">플랜 선택 :</span>                 <span className="user-write">{state.plan}</span>               </div>          

      추가로 SendRequest에서
      const state = location.state;
        console.log(state);
      출력해보니 TypeError: Cannot read properties of null (reading 'plan') 가 나오는데 전송이 왜 잘못된지를 모르겠습니다 ㅠ 

     
    #78801

    codingapple
    키 마스터
    폼내용을 state에 저장해서 props로 전달해주면 될듯요
    #79489

    이창민
    참가자
    쎈세 진짜 오래 고민을해봐도 답이나오지가 않습니다
    저렇게 navigate를써서 경로이동을하면 이동한곳에서 location 출력이되어야하는데 NULL값이 뜹니다 ㅠㅠ
    
    
    contact컴포넌트 코드
    const handleSubmit = async (e) => {
    // Add document to Firestore collection here
    try {
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    console.log(data);
    console.log(formData);
    await db.collection("contact").add({
    company: data.company,
    name: data.name,
    phone: data.phone,
    mail: data.mail,
    location: data.location,
    plan: data.plan,
    personnel: data.personnel,
    budget: data.budget,
     });
    alert("접수가 완료되었습니다.");
    // 페이지 이동, 데이터 전송
    navigate("/sendRequest", { state: { data } });
    e.target.reset();
     } catch (error) {
    console.error(error);
    alert("오류가 발생했습니다.");
     }
     };
    
    
    SendRequest코드
    import "./../Send-Request/SendRequest.css";
    import { useLocation } from "react-router-dom";
    function SendRequest() {
    const location = useLocation();
    const data = location.state?.data;
    console.log(data);
    // if (!data) {
    // return <div>실패시 출력함</div>;
    // }
    return (
    <div className="send-container">
    <h1 className="send-message">제출완료</h1>
    
    
    
    
     
    node  서버 코드입니다
    
    ...생략(대충 폼 데이터 다른 연결한곳으로 출력해달라는내용)
    출력 성공 이후 코드입니다.
    res.redirect("/sendRequest");
     } catch (err) {
    console.log(err.message);
    res.status(500).send("Error");
     }
    };
    module.exports = sendTodayData;
    app.post("/contact", sendTodayData);
    app.get("/sendRequest", function (req, res) {
    res.sendFile(path.join(__dirname, "cleanier-snack_react/build/index.html"));
    });
    
    app.js코드입니다
    
    unction App() {
    const [planName, setPlanName] = useState(""); // App.js에서 planName 상태 추가
    const handlePlanSelect = (plan) => {
    setPlanName(plan);
     };
    return (
    <div className="App">
    <Routes>
    <Route
    path="/"
    element={
    <>
    <Nav />
    <Banner />
    <Advangages />
    <Process />
    <Plan planName={planName} setPlanName={setPlanName} />
    <Review />
    <Contact planName={planName} setPlanName={setPlanName} />
    <Footer />
    <Tel />
    <Dropdowns
    planName={planName}
    handlePlanSelect={handlePlanSelect}
    />
    </>
    }
    />
    <Route
    path="/sendRequest"
    element={
    <>
    <Nav />
    <SendRequest />
    <Cleanier />
    <Footer />
    </>
    }
    ></Route>
    </Routes>
    </div>
     );
    }
    
    
     
     
    #79508

    codingapple
    키 마스터
    서버에서 redirect 해주면 새로고침되어서 state도 리셋될듯요 폼전송은 ajax 페이지이동은 navigate()만 씁시다
    #79543

    이창민
    참가자
    그럼 서버에서는 res.redirect('/sendRequest')를 새로고침되지않게
    res.send같은걸로 수정후
    (이것도 새로고침되던가용
    뭘써야하죠 ㅇㅅㅇ)
    contact컴포넌트에서 현재
    <form
    action="/contact"
    method="POST"
    className="form"
    onSubmit={handleSubmit}
    >
    이런식으로 데이터를 보내주고있는데 이거를 ajax요청(axios)로 보내면 되나요?
    #79640

    codingapple
    키 마스터
    서버는 .send 아니면 .json으로 메세지만 줍시다
    넴
    #79650

    이창민
    참가자
    사랑합니다 쎈세
7 글 보임 - 1 에서 7 까지 (총 7 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠