繁体   English   中英

将数组 state 从一个组件更新到另一个反应挂钩

[英]Update array state from one component to another react hooks

我正在尝试一个 MERN 博客网站项目。 目前,我在更新帖子评论时遇到问题。 我正在编辑来自另一个组件的评论,但在更新评论后我无法更新 state。 任何人都可以帮助我谢谢。

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>
                        )
                        
                    }) :""  
                }    

我不能肯定地说,因为显示评论的 React 组件不是完全可见的,但看起来你没有随时更新commentState 在我看来,它是空的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM