[英]How can I render Component with updated data after useEffect, the useEffect fetches data from an API
Basically what the code i want to do is after i click delete button it will re render the ActivityListScreen with the deleted Activity now gone in the list without refreshing the page.基本上我想要做的代码是在我单击删除按钮后,它将重新呈现 ActivityListScreen,其中已删除的 Activity 现在已在列表中消失,而无需刷新页面。 Right now i have to manually refresh the page to see the updated ActivityListScreen
现在我必须手动刷新页面才能看到更新的 ActivityListScreen
const ActivityListScreen = ({ history }) => {
const dispatch = useDispatch()
const getActivities = useSelector(state => state.getActivities)
const { activities, loading } = getActivities
const deleteActivity = useSelector(state => state.deleteActivity)
const { loading: del } = deleteActivity
useEffect(() => {
if (activities) {
dispatch(getActivitiesAction())
}
}, [dispatch])
const deleteHandler = (id) => {
dispatch(deleteActivityAction(id))
}
return (
<FormContainer>
<Row>
<Col className='d-flex '>
<LinkContainer to='/add'>
<Button className='ml-auto mb-3 btn-sm'>Add Activity</Button>
</LinkContainer>
</Col>
</Row>
{loading ? <h4>Please wait...</h4> : (
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Activity Name</th>
<th>Description</th>
<th>Date Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{activities && activities.map((activity) => (
<tr key={activity._id}>
<td>*</td>
<td>{activity.name}</td>
<td>{activity.description}</td>
<td>{moment(activity.createdAt).format('MMMM DD, YYYY')}</td>
<td className='d-flex justify-content-between border-0'><span><i className='fas fa-trash-alt' onClick={() => deleteHandler(activity._id)}></i></span>
<LinkContainer to={`edit/${activity._id}`}>
<span><i className='fas fa-edit'></i></span>
</LinkContainer>
</td>
</tr>
))}
</tbody>
</Table>
)}
</FormContainer>
)
}
export default ActivityListScreen
Basically what the code I want to do is after I click delete button it will re render the ActivityListScreen with the deleted Activity now gone in the list without refreshing the page.
基本上我想要做的代码是在我单击删除按钮后,它将重新呈现 ActivityListScreen,其中已删除的 Activity 现在已在列表中消失,而无需刷新页面。
useSelector
will automatically re-render the component when the state changes.当 state 更改时,
useSelector
将自动重新渲染组件。 You do not have to do anything special to get that behavior.你不必做任何特别的事情来获得这种行为。 What you are describing is what should happen automatically.
您所描述的是应该自动发生的事情。
Right now I have to manually refresh the page to see the updated ActivityListScreen
现在我必须手动刷新页面才能看到更新的 ActivityListScreen
This means that you have a mutation in your reducer.这意味着您的减速器中有突变。 You are probably mutating the existing
activities
array instead of (or in addition to) returning a new array.您可能正在改变现有的
activities
数组,而不是(或除此之外)返回一个新数组。
Either that or your deleteActivityAction
doesn't actually do anything and returns the same array.那个或你的
deleteActivityAction
实际上并没有做任何事情并返回相同的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.