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

home2 게시판 React 게시판 input 기능 복습/응용 중 문제 발생

input 기능 복습/응용 중 문제 발생

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

    Inpyo Lee
    참가자

    import './App.css';
    import { useState } from 'react';

    function App() {
      let [글제목, 글제목변경] = useState([{title : 'Love for Sale', date : '02/03/2000'}, {title : 'I Get A Kick Out Of You', date : '02/02/2000'}, {title : 'Night And Day', date : '02/01/2000'}]);
      
      let [글내용, 글내용변경] = useState([
        "'Love for Sale' is a song by Cole Porter introduced by Kathryn Crawford in the musical The New Yorkers, which opened on Broadway on December 8, 1930 and closed in May 1931 after 168 performances. The song is written from the viewpoint of a prostitute advertising 'love for sale'.",
        "'I Get a Kick Out of You' is a song by Cole Porter, which was first sung in the 1934 Broadway musical Anything Goes, and then in the 1936 film version. Originally sung by Ethel Merman, it has been covered by dozens of prominent performers, including Frank Sinatra, Dolly Parton, Ella Fitzgerald, and Tony Bennett with Lady Gaga. A cover in 1995 won the 1996 Grammy Award for Best Instrumental Arrangement with Accompanying Vocal(s) for arranger Rob McConnell while Bennett and Gaga's version is nominated for three awards at the 2022 ceremony.",
        "'Night and Day' is a popular song by Cole Porter that was written for the 1932 musical Gay Divorce. It is perhaps Porter's most popular contribution to the Great American Songbook and has been recorded by dozens of musicians."
      ]);

      let [좋아요, 좋아요변경] = useState([0,0,0]);
      function 좋아요변경디테일(i){
        let copy = [...좋아요];
        copy[i]++;
        좋아요변경(copy);
      }

      let [컨택트모달창, 컨택트모달창변경] = useState(false);
      let [컨택트모달버튼, 컨택트모달버튼변경] = useState('Contact Us Here');

      let [선택모달, 선택모달변경] = useState(undefined);

      let [새제목, 새제목변경] = useState('');
      function 제목추가(){
        let copy = [...글제목];

        let today = new Date();
        let year = today.getFullYear();
        let month = ('0'+(today.getMonth() + 1)).slice(-2);
        let day = ('0'+today.getDate()).slice(-2);
        let dateString = day + '/' + month + '/' + year;

        copy.unshift({ title : 새제목, date : dateString });
        글제목변경(copy);
      }

      let [새내용, 새내용변경] = useState('');
      function 내용추가(){
        let copy = [...글내용];
        copy.unshift(새내용);
        글내용변경(copy);
        console.log(글내용)
      }

      return (
        <div className="App">
          <header>
            <h1> Introducing Favourites of Mine </h1>
          </header>
         
          <div>
            <div>
              <label htmlFor='newTitle'>Title : </label>
              <input id='newTitle' name='newTitle' type='text' onChange={ (e)=>{
                새제목변경(e.target.value)
              } } />
            </div>
            <div>
              <textarea onChange={ (e)=>{ 새내용변경(e.target.value) } }></textarea>
            </div>
            <div>
              <button onClick={ ()=>{ 제목추가(); 내용추가(); console.log(글내용) } }>Add</button>
            </div>
          </div>

          <div className='listContainer'>
          {
            글제목.map((a,i)=>{
              return (
                <div className='list' key={i}>
                  <h3><span className='showModal' onClick={ ()=>{
                    선택모달변경(i)
                  } }>{a.title}</span> <span onClick={()=>{
                    좋아요변경디테일(i)
                  }}>👍</span> <span>{ 좋아요[i] }</span> </h3>
                  <p>{a.date}</p>
                </div>
              )
            })
          }
          </div>

         

          <div className='btnContainer'>
            <button className='btnMore' onClick={()=>{
              컨택트모달창===false
              ? 컨택트모달창변경(true)
              : 컨택트모달창변경(false)
              컨택트모달창===false
              ? 컨택트모달버튼변경('Hide Infos')
              : 컨택트모달버튼변경('Contact Us Here')
            }}>{ 컨택트모달버튼 }</button>
          </div>

          {
            컨택트모달창===true
            ? <InfoModal />
            : null
          }

          {
            선택모달>=0
            ? <SelectedModal 글제목={글제목} 선택모달={선택모달} />
            : null
          }

        </div>
      );
    }

    function InfoModal(){
      return (
        <div className='infoModal'>
          <h2>Contact us through&hellip;</h2>
          <a href='mailto:1992season@gmail.com'>1992season@gmail.com</a>
        </div>
      )
    }

    function SelectedModal(props){
      return (
        <div className='selectedModal'>
          <h2>{props.글제목[props.선택모달].title}</h2>
          <p>{props.글제목[props.선택모달].date}</p>
          <p>
            {props.글내용[props.선택모달]}
          </p>
        </div>
      )
    }

    export default App;

     

    안녕하세요!

    글 내용을 따로 state로 저장 후 input에는 제목, textarea에는 내용을 입력하여 저장할 수 있도록 해보았습니다. 일단 둘 다 저장은 잘 되어 게시글 목록에 추가된 듯 보였습니다. 하지만 제목 클릭 시 아래 모달창이 뜨는 '컨택트모달창' 기능이 정상작동하질 않게 되었습니다. 무엇이 문제일까요? 오류코드는 아래 복붙하겠습니다.

     

    App.js:185 Uncaught TypeError: Cannot read properties of undefined (reading '3')
    at SelectedModal (App.js:185)
    at renderWithHooks (react-dom.development.js:14985)
    at mountIndeterminateComponent (react-dom.development.js:17811)
    at beginWork (react-dom.development.js:19049)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
    at invokeGuardedCallback (react-dom.development.js:4056)
    at beginWork$1 (react-dom.development.js:23964)
    at performUnitOfWork (react-dom.development.js:22776)
    at workLoopSync (react-dom.development.js:22707)

    #24071

    codingapple
    키 마스터

    아마 네번째 글제목이나 내용같은게 없어서 나는 에러같습니다 

    새로운 글작성시 4번째 글제목이나 내용도 state에 추가합시다

     

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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