Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 页面刷新后内容消失_Reactjs - Fatal编程技术网

Reactjs 页面刷新后内容消失

Reactjs 页面刷新后内容消失,reactjs,Reactjs,我的react应用程序有问题。我有一个博客页面,在那里我可以创建博客文章并将其显示在屏幕上。在这一部分,一切正常。用户登录并可以编写帖子。每篇文章都包含一个阅读更多。。。链接,如果用户单击该链接,应用程序将重定向到实际的博客文章。在那里,用户可以阅读整个博客并添加一些评论。除了用户刷新页面外,一切都正常工作,控制台中的一切都会消失,没有任何错误。我使用firebase作为后端,一切都保存在那里,就像它必须保存一样。每次我点击特定的帖子,我都会被重定向到该帖子,一切正常,但当我刷新页面时,所有内容

我的react应用程序有问题。我有一个博客页面,在那里我可以创建博客文章并将其显示在屏幕上。在这一部分,一切正常。用户登录并可以编写帖子。每篇文章都包含一个阅读更多。。。链接,如果用户单击该链接,应用程序将重定向到实际的博客文章。在那里,用户可以阅读整个博客并添加一些评论。除了用户刷新页面外,一切都正常工作,控制台中的一切都会消失,没有任何错误。我使用firebase作为后端,一切都保存在那里,就像它必须保存一样。每次我点击特定的帖子,我都会被重定向到该帖子,一切正常,但当我刷新页面时,所有内容都会消失,帖子、评论,甚至输入字段和提交评论按钮

以下是刷新前的图片:

以下是刷新后的图片:

此外,我还将包括实际博客和评论部分的代码。 BlogAndCommentPage包含实际的博客文章,并保存评论和属于此文章的评论的输入字段

import React from 'react'
import { projectFirestore } from '../../firebase/config';
import BackToBlogs from './BackToBlogs'
import AddComment from '../commentComponents/AddComment'

class BlogAndCommentPage extends React.Component {
    state = { param: '', blog: [] }

    componentDidMount = () => {
        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString)
        const id = urlParams.get('id')
        this.setState({ param: id })

        const fetchDataFromFireBase = async () => {
            projectFirestore.collection('Blogs').doc(id).get()
                .then(doc => {
                    if(doc.exists) {
                        let document = [];
                        document.push(doc.data());
                        this.setState({ blog: document })
                    }
                })
        }

        fetchDataFromFireBase()
    }
    
    renderContent() {
        // Display the blog
        const blogs = this.state.blog?.map(value => {
            return (
                <div key={value.post.blogID}>
                    <h1>{value.post.title}</h1>
                    <h6>{`${value.post.name} - ${value.post.date}`}</h6>
                    <p>{value.post.body}</p>
                </div>
            )
        })
        return blogs;
    }

    render() {
        const displayedBlog = this.state.param
        return (
            <div>
                {
                    displayedBlog ? (
                        <div>
                        {this.renderContent()}
                        <BackToBlogs />
                        <hr></hr>
                        <h5 className="mb-2">Add a comment</h5>
                        <AddComment param={this.state.param} />
                        </div>
                    ) : ''
                }
            </div>
        )
    }
}

export default BlogAndCommentPage
从“React”导入React
从“../../firebase/config”导入{projectFirestore};
从“./BackToBlogs”导入积压日志
从“../commentComponents/AddComment”导入AddComment
类BlogAndCommentPage扩展了React.Component{
状态={param:'',博客:[]}
componentDidMount=()=>{
const queryString=window.location.search;
const urlParams=新的URLSearchParams(queryString)
const id=urlParams.get('id')
this.setState({param:id})
const fetchDataFromFireBase=async()=>{
projectFirestore.collection('Blogs').doc(id).get()
。然后(doc=>{
如果(文件存在){
让文档=[];
document.push(doc.data());
this.setState({blog:document})
}
})
}
fetchDataFromFireBase()
}
renderContent(){
//显示博客
const blogs=this.state.blog?.map(值=>{
返回(
{value.post.title}
{`${value.post.name}-${value.post.date}
{value.post.body}

) }) 返回博客; } render(){ const displayedBlog=this.state.param 返回( { 显示博客( {this.renderContent()}
添加评论 ) : '' } ) } } 导出默认BlogAndCommentPage
AddComment组件为注释和组件列表保留提交按钮

import React, { useState, useEffect } from 'react'
import SubmitComment from './SubmitComment'
import CommentHolder from './CommentHolder';
import { useSelector, useDispatch } from 'react-redux';

const AddComment = ({ param }) => {
    const [comment, setComment] = useState('');

    useEffect(() => {
        if (sessionStorage.getItem('user') === null) {
            alert('You are not logged in. Click OK to log in.')
            window.location = 'http://localhost:3000/'
        }
    }, [])

    const dispatch = useDispatch();
    const state = useSelector((state) => state.state);

    if (state) {
        setTimeout(() => {
            setComment('')
            dispatch({ type: "SET_FALSE" })
        }, 50)
    }

    return (
        <div>
            <div>
                <div className="row">
                    <div className="col-sm">
                        <div className="form-group">
                            <textarea rows="4" cols="50" placeholder="Comment" className="form-control mb-3" value={comment} onChange={(e) => setComment(e.target.value)} />
                        </div>
                    </div>
                </div>
            </div>
            <div className="mb-3">
                <SubmitComment comment={comment} param={param} />
            </div>
            <CommentHolder param={param} />
        </div>
    )
}

export default AddComment

import React,{useState,useffect}来自“React”
从“./SubmitComment”导入SubmitComment
从“/CommentHolder”导入CommentHolder;
从“react-redux”导入{useSelector,useDispatch};
const AddComment=({param})=>{
const[comment,setComment]=useState(“”);
useffect(()=>{
if(sessionStorage.getItem('user')==null){
警报('您未登录。单击“确定”登录')
window.location=http://localhost:3000/'
}
}, [])
const dispatch=usedpatch();
const state=useSelector((state)=>state.state);
如果(州){
设置超时(()=>{
setComment(“”)
分派({type:“SET_FALSE”})
}, 50)
}
返回(
setComment(e.target.value)}/>
)
}
导出默认的AddComment
CommentHolder呈现属于该帖子的每条评论

import React from 'react';
import { projectFirestore } from '../../firebase/config';
import DeleteComment from './DeleteComment'

class CommentHolder extends React.Component {

    state = { docs: [] }
    _isMounted = false;

    componentDidMount = () => {
        const fetchDataFromFireBase = async () => {
            const getData = await projectFirestore.collection("Comments")
            getData.onSnapshot((querySnapshot) => {
                var documents = [];
                querySnapshot.forEach((doc) => {
                    documents.push({ ...doc.data(), id: doc.id });
                });
                if (this._isMounted) {
                    this.setState({ docs: documents })
                }
            });
        }
        fetchDataFromFireBase()
        this._isMounted = true;
    }

    componentWillUnmount = () => {
        this._isMounted = false;
    }

    renderContent() {

        // Delete comments
        const deleteComment = async (id) => {
            projectFirestore.collection('Comments').doc(String(id)).delete().then(() => {
                console.log(`Blog with id: ${id} has been successfully deleted!`)
            })
        }

        // Build comments
        let user;
        if (sessionStorage.getItem('user') === null) {
            user = [];
        } else {
            user = JSON.parse(sessionStorage.getItem('user'));

            const commentArray = this.state.docs?.filter(value => value.blogID === this.props.param)
                .sort((a, b) => (a.time > b.time) ? -1 : (b.time > a.time) ? 1 : 0)
                    .map(comment => {
                return (
                    <div key={comment.id} className="card mb-3" >
                        <div className="card-body">
                            <div className="row">
                                <div className="col-sm">
                                    <h6>{`${comment.name} - ${comment.time}`}</h6>
                                    <p>{comment.comment}</p>
                                </div>
                                <div className="col-sm text-right">
                                    {user[0].id === comment.userID ? <DeleteComment commentid={comment.id} onDeleteComment={deleteComment} /> : ''}
                                </div>
                            </div>
                        </div>
                    </div>
                )
            });

            const updateComments = () => {
                const queryString = window.location.search;
                const urlParams = new URLSearchParams(queryString)
                const id = urlParams.get('id')

                const updateComment = projectFirestore.collection('Blogs').doc(id);
                return updateComment.update({
                    'post.comments': commentArray.length
                })
            }
            updateComments()
            return commentArray;

        }
    }

    render() {
        return (
            <div>
                {this.renderContent()}
            </div>
        )
    }
}

export default CommentHolder
从“React”导入React;
从“../../firebase/config”导入{projectFirestore};
从“/DeleteComment”导入DeleteComment
类CommentHolder扩展了React.Component{
状态={docs:[]}
_isMounted=错误;
componentDidMount=()=>{
const fetchDataFromFireBase=async()=>{
const getData=await projectFirestore.collection(“注释”)
getData.onSnapshot((querySnapshot)=>{
var文件=[];
querySnapshot.forEach((doc)=>{
push({…doc.data(),id:doc.id});
});
如果(此项已安装){
this.setState({docs:documents})
}
});
}
fetchDataFromFireBase()
这个。_isMounted=true;
}
组件将卸载=()=>{
这个。_isMounted=false;
}
renderContent(){
//删除评论
constdeletecoment=async(id)=>{
projectFirestore.collection('Comments').doc(字符串(id)).delete()。然后(()=>{
log(`Blog with id:${id}已成功删除!`)
})
}
//构建评论
让用户;
if(sessionStorage.getItem('user')==null){
用户=[];
}否则{
user=JSON.parse(sessionStorage.getItem('user'));
const commentArray=this.state.docs?.filter(value=>value.blogID==this.props.param)
.sort((a,b)=>(a.time>b.time)?-1:(b.time>a.time)?1:0)
.map(注释=>{
返回(
{`${comment.name}-${comment.time}`}
import React from 'react'

const DeleteComment = ({ commentid, onDeleteComment }) => {

    return (
        <div>
            <button onClick={() => onDeleteComment(commentid)} className='btn btn-outline-danger'>X</button>
        </div>
    )
}

export default DeleteComment

import React from 'react'
import { projectFirestore } from '../../firebase/config';
import { v4 as uuidv4 } from 'uuid';
import { useDispatch } from 'react-redux';

const SubmitComment = ({ comment, param }) => {

    const dispatch = useDispatch();

    const onCommentSubmit = () => {
        let user;
        if (sessionStorage.getItem('user') === null) {
            user = [];
        } else {
            user = JSON.parse(sessionStorage.getItem('user'));
            projectFirestore.collection('Comments').doc().set({
                id: uuidv4(),
                comment,
                name: `${user[0].firstName} ${user[0].lastName}`,
                userID: user[0].id,
                blogID: param,
                time: new Date().toLocaleString()
            })

            dispatch({ type: "SET_TRUE" });
        }
    }

    

    return (
        <div>
            <button onClick={() => onCommentSubmit()} className='btn btn-primary'>Add comment</button>
        </div>
    )
}

export default SubmitComment

    return (
        <Router >
            <Route path='/content-page' exact render={(props) => (
                <>
                    <BlogAndCommentPage />
                </>
            )} />
            <Route path='/blogpage' exact render={(props) => (
                <>
                    <div>
                        <div className="row">
                            <div className="col-8">
                                <h1 className='mb-3'>Blog</h1>
                            </div>
                            <div className="col-4 mb-3">
                                <LogoutButton onLogOut={logout} />
                                <h6 className='float-right mt-4 mr-2'>{displayUser}</h6>
                            </div>
                        </div>
                        {empty ? (<div style={{ color: "red", backgroundColor: "#F39189", borderColor: "red", borderStyle: "solid", borderRadius: "5px", textAlign: 'center' }} className="mb-2">Title and body cannot be blank</div>
                        ) : ("")}
                        <InputArea getBlogContent={getBlogContent} />
                        <CreateBlog post={post} onCheckEmptyInputs={checkEmptyTitleAndBody} />
                        <hr />
                        <BlogHolder />
                    </div>
                </>
            )} />

        </Router>

    )