[英]How to re-render component with react hooks
我是React的新手,正在尝试使用React Hooks。 我有一个基于功能的组件,并且正在使用useState
和useEffect
从数据库中获取用户并将其显示在表中。
现在,我在表格的每一行都有一个删除按钮。 当我单击删除按钮时,我执行删除功能,该功能从数据库中删除数据。 这很好。 但是,除非我完全刷新整个页面,否则不会更新该表。
删除完成后,如何更新(重新呈现)用户表。
以下是我的代码片段:
const [users, listUsers] = React.useState([]);
React.useEffect(() => {
axios
.get(GET_URL)
.then(res => {
console.log(res.data);
listUsers(res.data);
})
.catch(err => console.log(err));
}, []);
const deleteUser = async id => {
await fetch(DELETE_URL, {
//JSon message
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
user_id: id
})
})
.then(response => response.text())
.then(responseJson => {
console.log(JSON.stringify(responseJson));
})
.catch(error => {
console.error(error);
});
alert('User Deleted.');
};
一旦删除,您就不会更新用户列表状态。您已经更新了用户列表状态。 您可以通过以下方式做到这一点:
const deleteUser = async id => {
await fetch(DELETE_URL, {
//JSon message
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
user_id: id
})
})
.then(response => response.text())
.then(responseJson => {
console.log(JSON.stringify(responseJson));
})
.catch(error => {
console.error(error);
});
const usersUpdated = users.filter(p => p.id !== id); //Filter your list of users and remove the one for the specific id
listUsers(usersUpdated); //This updates your state
alert('User Deleted.');
};
;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.