Обновить состояние массива от одного компонента к другому. - PullRequest
0 голосов
/ 05 августа 2020

Я пытаюсь создать проект сайта блога MERN. В настоящее время я столкнулся с проблемой при обновлении комментария к сообщению. Я редактирую комментарий из другого компонента, но не могу обновить состояние после обновления комментария. Всем, кто поможет мне, спасибо.

Код клиента для компонента EditComment:

    import React, { Fragment, useState } from 'react';
import Input from '../components/Input';
import Axios from 'axios';

export const EditComment = (props) => {
    const [commentBody, setComment] = useState(props.comment.commentBody);
    console.log(props.comment._id)
    const [commentState, setCommentState] = useState([props.cmtState]);


    const handleChange = (event) => {
        const { value, name } = event.target
        setComment(value)
    }

    console.log(commentBody)

    const handleCommentEdit = async (postid, commentid) => {
        try {
            const res = await Axios.patch(`/api/posts/${postid}/comments/${commentid}`,JSON.stringify({commentBody}), {
                headers: {
                    "Content-Type": "application/json",
                    'Authorization': 'Bearer ' +localStorage.getItem('token')
                }
            })
            setCommentState(prevValue => {
                return [...prevValue, res.data.info]
            });
            console.log(res)
        } catch (error) {
            console.log( error.response.request );
        }
    }

    return(
        <Fragment>
            <i 
                data-toggle="modal" data-target={`#exampleModal${props.comment._id}`}
                className="fa fa-pencil ml-3" 
                style={{color: "blue", cursor: 'pointer'}}></i>
            <div 
                className="modal fade" 
                id={`exampleModal${props.comment._id}`} 
                tabIndex="-1" role="dialog" 
                aria-labelledby="exampleModalLabel" 
                aria-hidden="true">
            <div className="modal-dialog" role="document">
                <div className="modal-content">
                <div className="modal-header">
                    <h5 
                        className="modal-title" 
                        id="exampleModalLabel">Modal title</h5>
                    <button 
                        type="button" 
                        className="close" 
                        data-dismiss="modal" 
                        aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div className="modal-body">
                    <Input 
                        type="text" 
                        name="commentBody" 
                        value={commentBody} 
                        onChange={ handleChange } 
                        className="form-control" />
                </div>
                <div className="modal-footer">
                    <button 
                        type="button" 
                        className="btn btn-secondary" 
                        data-dismiss="modal">Close</button>
                    <button 
                        type="button" 
                        onClick={() => handleCommentEdit(props.postid, props.comment._id)}
                        data-dismiss="modal"
                        className="btn btn-warning">Save changes</button>
                </div>
                </div>
            </div>
            </div>
        </Fragment>
    )
}

Код клиента для отображения комментария (где нужно отображать состояние обновления):

 const [commentBody, setComment] = useState('');
    const [commentState, setCommentState] = useState([]);
 <h6>Comments</h6>
                {
                    commentState.length > 0 ? commentState.map((comment, index) => {
                        return(
                            <div key={index} className="mb-2">
                                <span className="mr-2">{comment.commentBody}</span>
                                <span className="mr-2 text-primary"><em>-{comment.commentBy.name}</em></span>
                                <span className="text-secondary"><em>{formatDate(comment.createdAt)}</em></span>
                                {
                                    authContext.userState.user && authContext.userState.user._id === comment.commentBy._id &&
                                    <Fragment>
                                        <EditComment cmtState={commentState} comment={comment} postid={postid}/>
                                        <i 
                                            className="fa fa-trash ml-3" 
                                            onClick={() => handleCommentDelete(postid, comment._id)}  
                                            style={{color: "red", cursor: 'pointer'}}></i>
                                    </Fragment>
                                }
                                
                            </div>
                        )
                        
                    }) :""  
                }    

1 Ответ

0 голосов
/ 05 августа 2020

Я не могу сказать наверняка, поскольку компонент React для отображения комментариев не полностью виден, но похоже, что вы не обновляете commentState в любое время. Мне кажется, он так и остается пустым.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...