• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

안녕하세요 감정일기 글 수정간 slice is not a function 으로 나와서 진도가 막혀있네요 ㅠ slice(0,25)부분에 에러가뜹니다

22.04.27 06:51 작성 조회수 889

0

DiaryItem.js부
 
import MyButton from "./MyButton";
import {useNavigate} from "react-router-dom";
const DiaryItem = ({ id, emotion, content, date}) => {

    const env = process.env;
    env.PUBLIC_URL = env.PUBLIC_URL || "";    
    const navigate = useNavigate();
    const strDate = new Date(parseInt(date)).toLocaleDateString();
    const goDetail = ()=>{
        navigate(`/diary/${id}`);
    }
    const goEdit = ()=>{
        navigate(`/edit/${id}`);
    }

    return(
    <div className="DiaryItem">
        <div
        onClick={goDetail}
        className={[
        "emotion_img_wrapper",
        `emotion_img_wrapper_${emotion}`,
        ].join(" ")}>
            <img src={process.env.PUBLIC_URL + `assets/emotion${emotion}.png`}></img>
        </div>
        <div
         onClick={goDetail}
         className="info_wrapper">
            <div className="diary_date">{strDate}</div>
            <div className="diary_content_preview">{content.slice(0,25)}</div>
        </div>
        <div className="btn_wrapper">
            <MyButton onClick={goEdit} text={"수정하기"} />
        </div>
    </div>

    );
};

export default DiaryItem;
 
 
 
 
 
 
---------------------------------------------------------------------------------------------------
DiaryEditor.js
 
import {useNavigate} from "react-router-dom";
import {useState,useRef,useContext, useEffect} from "react";
import {DiaryDispatchContext} from "./../App.js";

import MyButton from './MyButton';
import MyHeader from './MyHeader';
import EmotionItem from "./EmotionItem";
export const getStringDate = (date) => {

    let year = date.getFullYear();
 
    let month = date.getMonth() + 1;
 
    let day = date.getDate();
 
    if (month < 10) {
 
      month = `0${month}`;
 
    }
 
    if (day < 10) {
 
      day = `0${day}`;
 
    }
 
    return `${year}-${month}-${day}`;
 
  };
const emotionList =
[
  {
    emotion_id : 1,
    emotion_img : process.env.PUBLIC_URL + `/assets/emotion1.png`,
    emotion_descript:'완전 좋음',
  },
  {
    emotion_id : 2,
    emotion_img : process.env.PUBLIC_URL + `/assets/emotion2.png`,
    emotion_descript:'좋음',
  },
  {
    emotion_id : 3,
    emotion_img : process.env.PUBLIC_URL + `/assets/emotion3.png`,
    emotion_descript:'보통',
  },
  {
    emotion_id : 4,
    emotion_img : process.env.PUBLIC_URL + `/assets/emotion4.png`,
    emotion_descript:'나쁨',
  },
  {
    emotion_id : 5,
    emotion_img : process.env.PUBLIC_URL + `/assets/emotion5.png`,
    emotion_descript:'매우 나쁨',
  },
]
   
const DiaryEditor = ({isEdit,originData}) =>
{
   
    const navigate = useNavigate(new Date(getStringDate));
   
 
    const contentRef = useRef();
    const [content,setContent]=useState("");
    const [emotion,setEmotion] =useState(3);

    const [date, setDate] = useState(getStringDate(new Date()));
   
    const {onCreate,onEdit} = useContext(DiaryDispatchContext);
    const handleClickEmotion = (emotion)=>{
      setEmotion(emotion);
    };
 
    const handleSubmit = () => {
      if(content.length <1){
        contentRef.current.focus();
        return;
      }
      if(window.confirm(
        isEdit? "일기를 수정하시겠습니까?" :"새로운 일기를 작성하시겠습니까?")){
        if(!isEdit)
        {
          onCreate(date,content,emotion);
        }
        else
        {
          console.log(originData);
          onEdit(originData.id, date, content, emotion);
        }
      }
     
      navigate("/",{ replace : true });
    };

    useEffect(() => {
      if(isEdit){
        setDate(getStringDate(new Date(parseInt(originData.date))));
        setEmotion(originData.emotion);
        setContent(originData.content);
      }
    }, [isEdit, originData]);

    return(
       
    <div  className="DiaryEditor">
        <MyHeader
        headText = {isEdit ? " 일기수정하기 " : " 새 일기쓰기 "}
        leftChild = {
        <MyButton text={"< 뒤로가기"} onClick={()=>navigate(-1)}/>
        }
        />
        <div>
            <section>
            <h4>오늘은 언제인가요?</h4>
            <div className="input_box"></div>
            <input className="input_date" value={date}
            onChange ={(e)=>setDate(e.target.value)}
            type="date"
            />
            </section>
            <section>
              <h4>오늘의 감정</h4>
              <div className="input_box emotion_list_wrapper">
                {emotionList.map((it)=> (
              <EmotionItem
              key={it.emotion_id}
              {...it}
              onClick={handleClickEmotion}
              isSelected={it.emotion_id  === emotion}
              />
                ))}
              </div>
            </section>
            <section>
              <h4>오늘의 일기</h4>
              <textarea placeholder="오늘 하루 어땠어요?"
              ref={contentRef}
              value={content}
              onChange={(e)=>setContent(e.target.value)}/>
            </section>
            <section>
                  <div className="control_box">
                    <MyButton text={"취소하기"} onClick={() => navigate(-1)}/>
                    <MyButton text={"작성하기"} type={'positive'} onClick={handleSubmit}/>

                  </div>

            </section>
        </div>
    </div>
    );
}
export default DiaryEditor;
 
 
 
 
 
 

답변 1

답변을 작성해보세요.

1

안녕하세요

강사 이정환입니다

 

구체적인 오류의 원인은 CodeSandbox를 통해 코드를 직접 살펴봐야 알겠지만

slice is not function 오류는 거의 content가 undefined이기 때문에 발생합니다.

DiaryItem에서 받은 props 중 content의 값이 정상적으로 문자열이 들어오는지 확인 해 보세요

kyn00018님의 프로필

kyn00018

질문자

2022.04.27

content 값 확인해보니 더미게시물 6개중 6개 들어오는것 확인했습니다.. 

kyn00018님의 프로필

kyn00018

질문자

2022.04.27

글쓰기는 정상인데 수정할때에 문제가있는거면  수정화면, diaryItems부분을 보면될까요?

kyn00018님의 프로필

kyn00018

질문자

2022.04.27

그래서 혹시나해서 content slice빼고 console.log찍어봤습니다.

kyn00018님의 프로필

kyn00018

질문자

2022.04.27

번거롭게 해드리는것 같아서 죄송하기도 하네요 ..!

강의 여러번 영상돌려보면서 해봤지만 아직 해결이 안된것 같아서 ..

1)DiaryItem.js:32 Uncaught TypeError: content.slice is not a function

2)react_devtools_backend.js:3973 The above error occurred in the <DiaryItem> component:

Consider adding an error boundary to your tree to customize error handling behavior.

Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

 

이 두가지가 뜹니다. DiaryItem부분 컴포넌트에서 문제가 있다는것 같은데 컴포넌트 불러오는 DirayEditor,DiaryItem 모두확인해 봤으나 아직 답이 안나오네요 ㅠ

 

혹시 가능하시면 강의에 사용된 소스코드 공유 부탁드려도될까요?