인프런 커뮤니티 질문&답변

learn님의 프로필 이미지
learn

작성한 질문수

React로 NodeBird SNS 만들기

댓글의 댓글을 달려면 어떻게 해야되나요?

작성

·

270

0

강의에서 MainPosts는 MainMessage로 Comments는 MainContents로 

치환을 해서 대화목록 만들고 그 안에서 글을 작성하는 건 되는데 

그 글에서 댓글을 다는 게 안되서 질문 드립니다 그 글에서 댓글은 Comments로 정의했고

reducers/message.js Comment 부분

export const initialState = {
    mainMessages: [{
        id: 1,
        User: {
            id: 1,
            name: '이수현',
        },
        Others: [{
            id: 2,
            name: '김민지',

        },
        {
            id: 3,
            name: '이우리',

        }],
        mainContents: [{
            id: 1,
            User: {
                id: 2,
                name: '이수현',
                avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
            },
            content: '안녕',
            img: 'https://images.unsplash.com/photo-1484480974693-6ca0a78fb36b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1952&q=80',
            Comments: [],
        },
        {
            id: 2,
            User: {
                id: 1,
                name: '김민지',
                avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
            },
            content: '안농',
            img: 'https://images.unsplash.com/photo-1484480974693-6ca0a78fb36b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1952&q=80',
            Comments: [],
        }],

    }],
    imagePaths: [],
    addMessageErrorReason: '',
    isAddingMessage: false,
    MessageAdded: false,

    isAddingContent: false,
    addContentErrorReason: '',
    contentAdded: false,

    isAddingComment: false,
    addCommentErrorReason: '',
    commentAdded: false,
}
const dummyContent = {
    id: 3,
    User: {
        id: 6,
        name: '김하나',
        avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
    },
    content: '더미 댓글입니다.',
    img: 'https://images.unsplash.com/photo-1484480974693-6ca0a78fb36b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1952&q=80',
    Comments: [],
    createdAt: new Date(),
}
case ADD_COMMENT_REQUEST:{
            return{
                ...state,
                isAddingComment: true,
                addCommentErrorReason:'',
                commentAdded: false,
            };
        }
        case ADD_COMMENT_SUCCESS:{
            const messageIndex = state.mainMessages.findIndex(v => v.id === action.data.messageId);
            const message = state.mainMessages[messageIndex];
            const contentIndex = message.mainContents.findIndex(v => v.id === action.data.contentId);
            const content = state.mainBoards[contentIndex];
            const Comments = [...content.CommentsdummyComment];
            const mainContents = [...state.mainContents];
            mainContents[contentIndex] = {...contentComments};
            return{
                ...state,
                isAddingComment: false,
                mainMessages,
                mainContents,
                commentAdded: true,
            };
        }
        case ADD_COMMENT_FAILURE:{
            return{
                ...state,
                isAddingComment:false,
                addCommentErrorReason: action.error,

            };
       }

sagas/message.js

function addCommentAPI(){

}
function* addComment(action) {
    try{
        yield delay(2000);
        yield put({
            type: ADD_COMMENT_SUCCESS,
            data: {
                messageId: action.data.messageId,
                contentId: action.data.contentId,
            },
        });
    }catch (e) {
        yield put({
            type: ADD_COMMENT_FAILURE,
            error: e,
        });
    }
}
function* watchAddComment() {
    yield takeLatest(ADD_COMMENT_REQUESTaddComment);
}

pages/messageCard.js

    return (
        <div>
            {message.mainContents.map((v=> {
                return (
                    <>
                        <Comment
                            actions={[
                                <span key="comment-basic-like">
                                    <Tooltip title="Like">
                                        {React.createElement(action === 'liked' ? LikeFilled : LikeOutlined, {
                                            onClick: like,
                                        })}
                                    </Tooltip>
                                    <span className="comment-action">{likes}</span>
                                </span>,
                                <span key=' key="comment-basic-dislike"'>
                                    <Tooltip title="Dislike">
                                        {React.createElement(action === 'liked' ? DislikeFilled : DislikeOutlined, {
                                            onClick: dislike,
                                        })}
                                    </Tooltip>
                                    <span className="comment-action">{dislikes}</span>
                                </span>,
                                // <span key="comment-basic-reply-to"><Icon type ="message" key="message" onClick={onToggleComment}/></span>,
                                <span key="comment-basic-reply-to">
                                    <Tooltip title="Reply">
                                        {React.createElement(action === 'reply' ? MessageFilled : MessageOutlined, {
                                            onClick: () => {
                                                setContentIdState(v.id);
                                                console.log(v.id);
                                            },
                                        })}
                                    </Tooltip>
                                    {/* <span className="comment-action">{dislikes}</span> */}
                                </span>,
                            ]}
                            author={<a>{v.User.name}</a>}
                            avatar={
                                <Avatar
                                    src={v.User.avatar}
                                // alt="Han Solo"
                                />
                            }
                            content={
                                <p>
                                    {v.content}
                                </p>
                            }
                            datetime={
                                <Tooltip title={moment().format('YYYY-MM-DD HH:mm:ss')}>
                                    <span>{moment().fromNow()}</span>
                                </Tooltip>
                            }
                        >
                            {/* {v.id == contentId?<MessageCardComment content={v} key={v}/>: <></>} */}
                            {v.id == contentId ?
                                <>
                                    <Form onSubmit={(e=> {
                                        e.preventDefault();
                                        if (!user) {
                                            return alert('로그인이 필요합니다.');
                                        }
                                        dispatch({
                                            type: ADD_COMMENT_REQUEST,
                                            data: {
                                                messageId: message.id,
                                                contentId: v.id,
                                            },
                                        })
                                    }}>
                                        <Form.Item>
                                            <Input.TextArea rows={4} value={commentText} onChange={onChangeCommentText} />
                                        </Form.Item>
                                        <Button type="primary" htmlType="submit" loading={isAddingComment}>입력</Button>
                                    </Form>
                                    <List
                                        header={`${v.Comments ? v.Comments.length : 0} 댓글`}
                                        itemLayout="horizontal"
                                        dataSource={v.Comments || []}
                                        renderItem={item => (
                                            <li>
                                                <Comment
                                                    author={item.User.name}
                                                    avatar={<Avatar>{item.User.name[0]}</Avatar>}
                                                    content={item.content}
                                                //   datetime={item.createdAt}
                                                />
                                            </li>
                                        )}
                                    />
                                </>
                                : <></>}
                        </Comment>
                        <Divider />
                    </>
                )
            })}
        </div>
   );

저렇게 MessageId하고 ContentId를 두개를 넘기나요? 넘겼는데 자꾸 FAILURE라고 떠서 

그리고 저기서 원래 onSubmitCommentForm을 함수로 빼려고 했는데 그럼 v.id 범위를 벗어나서 안에다가 넣었는데 함수로 하고 싶으면 onSubmitCommentForm(v.id)를 넣어줘도 되는 건가요? 

만약 저기서 댓글의 댓글을 추가한다고 하면 messageId, contentId, commentId가 다 필요한 건가요? 그럼 그 변수는 props 여러개로 넘기는 건가요? 아니면 저렇게 한페이지에 있어야되는 건가요..? 

답변 2

0

learn님의 프로필 이미지
learn
질문자

아 아직 리트윗은 안봤는데 그거 듣고 다시 해볼께요 감사합니다! 

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

혹시 리트윗 만드는 부분 강좌 보셨나요?? 그런식으로 대댓글도 똑같이 ParentId같은 것 db에 관계 설정해서 넣어주시면 됩니다. onSubmit함수는 대댓글인 경우 게시글아이디 내용 부모댓글아이디 모두 필요합니다.

learn님의 프로필 이미지
learn

작성한 질문수

질문하기