reactjs React提取方法删除刷新页面

mzsu5hc0  于 2023-02-22  发布在  React
关注(0)|答案(3)|浏览(144)

我正在react中制作一个应用程序,在抓取删除后浏览器重新加载。有什么提示吗?按照下面的代码操作。当我尝试删除一个项目时,尤其是当我创建一个新项目然后删除它时,会出现错误。然后,由于浏览器刷新而包含项目的消息出现。从下面的代码中,我想你可以找到错误,但如果你需要它,它也在github上,提前感谢。

import { useState, useEffect } from 'react'

import Message from '../layout/Message'
import Container from '../layout/Container'
import Loading from '../layout/Loading'
import LinkButton from '../layout/LinkButton'
import ProjectCard from '../project/ProjectCard'

import styles from './Projects.module.css'

function Projects(){
    const [projects, setProjects] = useState([])
    const [removeLoading, setRemoveLoading] = useState(false)
    const [projectMessage, setProjectMessage] = useState('')

    const location = useLocation()
    let message = ''

    if(location.state){        
        message = location.state.message
    }

    useEffect(() => {setTimeout(() => {
            fetch('http://localhost:5000/projects', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },  
            })
            .then((resp) => resp.json())
            .then((data) => {  
                console.log(data)
                setProjects(data)  
                setRemoveLoading(true)
                
                //setProjects('');
                //console.log(projects)          
            })                
            .catch((err) => console.log(err))

        }, 300)
    }, [])    

    //console.log(location)

    function removeProject(id){        
        fetch(`http://localhost:5000/projects/${id}`,{
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
        }).then(resp => resp.json())
        .then(data => {            
            setProjects(projects.filter((project) => project.id !== id))
            setProjectMessage('Projeto removido com sucesso!')
        })
        .catch(err => console.log(err))    
    }

    return (
        <div className={styles.project_container}>
            <div className={styles.title_container}>
                <h1>Meus Projetos</h1>
                <LinkButton to="/newproject" text="Criar Projeto"/>
            </div>             
            {message && <Message type="success" msg={message}/>}
            {projectMessage && <Message type="success" msg={projectMessage}/>}
            <Container customClass="start">
                {projects.length > 0 &&                 
                projects.map(project => (                    
                    <ProjectCard                     
                        name={project.name} 
                        id={project.id}
                        budget={project.budget}
                        category={project.category.name}                         
                        key={project.id}
                        handleRemove={removeProject}                           
                    />                    
                ))}
                {!removeLoading && <Loading/>}
                {removeLoading && projects.length === 0 && (
                   <p>Não há projetos cadastrados!</p> 
                )}
            </Container>
        </div>
    )
}

export default Projects


import { Link } from 'react-router-dom'
import styles from './ProjectCard.module.css'

import { BsPencil, BsFillTrashFill } from 'react-icons/bs'

//function ProjectCard({name, id, budget, category, key}){
function ProjectCard(props){
    //alert({name})
    //console.log({category})

    const remove = (e) => {
    //function remove (e) {
        //console.log(e)        
        e.preventDefault()
        props.handleRemove(props.id)
        
        //console.log('teste')
        //e.stopPropagation();
        //e.nativeEvent.stopImmediatePropagation();
    }    

    return(         
        <div className={styles.project_card}>
            <h4>{props.name}</h4>  
            <p>
                <span>Orçamento</span> R${props.budget}
            </p>
            <p className={styles.category_text}>
                <span className={`${styles[props.category.toLowerCase()]}`}></span> {props.category}
            </p>
            <div className={styles.project_card_actions}>
                <Link to="/">
                   <BsPencil/> Editar 
                </Link>
                <button onClick={remove}>
                    <BsFillTrashFill/> Excluir
                </button>
            </div>
        </div>
    )
}

export default ProjectCard


import { useNavigate } from 'react-router-dom'
import ProjectForm from '../project/ProjectForm'

import styles from './NewProject.module.css'

function NewProject(){

  const navigate  = useNavigate()

  function createPost(project){
    // initialize cost and services
    project.cost = 0
    project.services = []       

    fetch("http://localhost:5000/projects",{
      method: 'POST',
      headers: {
        'Content-type': 'application/json'      
      },
      body: JSON.stringify(project),
    }).then((resp) => resp.json())
    .then((data) => {
      //console.log(data)
      //redirect      
      navigate('/projects', {
        state: {
          message: "Projeto criado com sucesso!",
        }
      });
    })
    .catch((err) => console.log(err))    

  return (
    <div className={styles.newprojectcontainer}> 
      <h1>Criar Projeto</h1>
      <p>Crie seus projetos para depois adicionar os seriços.</p>
      <ProjectForm handleSubmit={createPost} btnText="Criar Projeto"/>
    </div>  
  )
}
}

export default NewProject```
x7rlezfr

x7rlezfr1#

尝试像这样将type="button"添加到button元素中:

<button type="button" onClick={remove}>
    <BsFillTrashFill/> Excluir
 </button>
8wigbo56

8wigbo562#

dbidojson文件在公共文件夹中。我创建了一个名为data的文件夹并将其放入其中,刷新停止了...奇怪...:)

bz4sfanl

bz4sfanl3#

我不知道为什么...但是如果你把json文件放在公共文件夹中,当你提取(在我的例子中是删除方法)时,它总是会刷新react应用程序,这很奇怪...如果有人对此有解释,请告诉我们。
现在,一旦我将JSON文件移动到src文件夹,它就可以很好地工作,没有任何奇怪的刷新!!

相关问题