如何在数据更改后仅重新渲染组件一次?

How to Re-render Component Only Once after the data is changed?

我是 React JS 的新手。我正在 React 中进行 CRUD 操作。一切都很好,但是当我从列表中删除项目时,我必须刷新浏览器来更新列表。我该如何解决?

import React, { useState, useEffect } from 'react'
import axios from 'axios';
import { Segment, Item, Container, Card, Icon, Button } from 'semantic-ui-react';
import { IEmployee } from '../../src/Model/activity'
import { Link, RouteComponentProps } from 'react-router-dom';


interface DetailParams {
    id: string;
}


const EmployeeList : React.FC<RouteComponentProps<DetailParams>> = ({ match, history }) => {

    const [employees, setEmployees] = useState<IEmployee[]>([])

    useEffect(() => {
        axios.get('https://localhost:44353/Employee/GetEmployeeList')
            .then((response) => {
                setEmployees(response.data)
            })
    }, [])


    const deleteEmployee =(id: string) => {
        axios.get(`https://localhost:44353/Employee/DeleteEmployee/${id}`)
            .then((response) => {
            history.push('/employeeList')
        })
    }

    return (
        <Container style={{ marginTop: '7em' }}>
            <Segment>
                {
                    employees.map(employee => (
                            <Card key={employee.id}>
                                {/* <Image src='/images/avatar/large/daniel.jpg' wrapped ui={false} /> */}
                                <Card.Content>
                                    <Card.Header>{employee.firstName}</Card.Header>
                                    <Card.Meta>{employee.address}</Card.Meta>
                                        <Card.Description>
                                     {employee.organization}
                                </Card.Description>
                                </Card.Content>

                             <Card.Content>
                             
                             
                             <Button
                               
                                onClick={() => deleteEmployee(employee.id)}
                                floated="right"
                                content="Delete"
                                color="red" />

                             <Button
                                as={Link} to={`/edit/${employee.id}`}
                                floated="right"
                                content="View"
                                color="blue" />

                             </Card.Content>

                            </Card>
                    ))
                }
            </Segment>
        </Container>
    )
}

export default EmployeeList

以上代码为 EmployeeList 组件,由 ** /employeeList ** 路由。这是代码的 UI

当我从列表中删除项目时,我需要重新加载浏览器以更新列表。我尝试在 useEffect

中使用 employee dependent
useEffect(() => {
        axios.get('https://localhost:44353/Employee/GetEmployeeList')
            .then((response) => {
                setEmployees(response.data)
            })
    }, [employees])

这工作正常,但 API 方法正在无限执行。我该如何解决?

可以做两件事

  1. 如果您删除 api returns 更新数据,您只需调用 setEmployess 并设置更新值即可。

  2. 或者您可以从状态 employees

    中筛选已删除的值
    const deleteEmployee =(id: string) => {
     //add this in axios call success
         let updatedEmployee = [...employees];
         updatedEmployee.filter(eachEmployee=>eachEmployee.id !== id);
         setEmployees(updatedEmployee);
    
    
     }
    

您不应刷新页面,而应在删除请求后再次发出请求以获取更新的员工列表。

const deleteEmployee = async (id: string) => {
    // Delete employee
    await axios.get(`https://localhost:44353/Employee/DeleteEmployee/${id}`)
    
    // Get a fresh list 
    const employees = (await axios.get('https://localhost:44353/Employee/GetEmployeeList')).data
    setEmployees(employees)
    
    // Navigate
    history.push('/employeeList')

}