简体   繁体   English

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

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

I am new to React JS.我是 React JS 的新手。 I am making CRUD Operation in React.我正在 React 中进行 CRUD 操作。 Everything is fine but when I delete the item from the list I have to refresh the browser tho update the List.一切都很好,但是当我从列表中删除项目时,我必须刷新浏览器才能更新列表。 How can I solve this?我该如何解决这个问题?

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

The above code is of EmployeeList Component which is routed by ** /employeeList **.上面的代码是由 ** /employeeList ** 路由的 EmployeeList 组件。 Here is the UI of the code这是代码的用户界面在此处输入图像描述

when I delete the item from the list I need to reload the browser to update the List.当我从列表中删除项目时,我需要重新加载浏览器以更新列表。 I tried using employee dependent in useEffect我尝试在 useEffect 中使用员工依赖

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

this worked fine but the API method is executing infinitely.这工作正常,但 API 方法正在无限执行。 How do I solve this?我该如何解决这个问题?

Two things can be done可以做两件事

  1. if your delete api returns the updated data you can just call setEmployess and set the updated value.如果您删除 api 返回更新的数据,您只需调用setEmployess并设置更新的值。

  2. or you can filter the deleted value from the state employees或者您可以从 state employees中过滤删除的值

    const deleteEmployee =(id: string) => { //add this in axios call success let updatedEmployee = [...employees]; updatedEmployee.filter(eachEmployee=>eachEmployee.id;== id); setEmployees(updatedEmployee); }

Instead of refreshing the page you should just make another request after the delete request to get an updated employees list.而不是刷新页面,您应该在删除请求后发出另一个请求以获取更新的员工列表。

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')

}

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

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