저는 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에서 직원 의존을 사용해 보았습니다.
useEffect(() => {
axios.get('https://localhost:44353/Employee/GetEmployeeList')
.then((response) => {
setEmployees(response.data)
})
}, [employees])
이것은 잘 작동했지만 API 메서드는 무한히 실행됩니다. 이 문제를 어떻게 해결합니까?
두 가지를 할 수 있습니다
삭제 API가 업데이트 된 데이터를 반환하는 setEmployess
경우 업데이트 된 값을 호출 하고 설정할 수 있습니다 .
또는 상태에서 삭제 된 값을 필터링 할 수 있습니다. employees
const deleteEmployee =(id: string) => {
//add this in axios call success
let updatedEmployee = [...employees];
updatedEmployee.filter(eachEmployee=>eachEmployee.id !== id);
setEmployees(updatedEmployee);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다