在反应钩子中删除后未刷新的数据



删除记录后,玩家数据仍显示在主屏幕中,并且不会刷新。只有在导航到其他屏幕后,我才能在主屏幕中看到更新的数据。

我尝试将setSearchResults(searchResults)状态放入onDelete()但不起作用。

Home.js

以下是在主屏幕中显示玩家数据的 get 方法:

const [playerList, setPlayerList] = useState([]);
const [searchResults, setSearchResults] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const res = await Axios.get('http://localhost:8000/service/players');
if (isMounted.current) {
setPlayerList(res.data.players);
setSearchResults(res.data.players);
const privilege = localStorage.getItem('Privilege');
console.log("What is getting in Front End:" + privilege);
showDeleteIcon(privilege);
}
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);

const onDelete = id => () => {
try {
Axios.delete('http://localhost:8000/service/player', {
headers: {
'Content-Type': 'application/json'
},
data: {
'id' : id
}
});
setDeleteDialog(false);
//setSearchResults(searchResults);
//setPlayerList(playerList);
} catch (e) {
console.log(e);
}
}

server.js

app.delete('/service/player', async (req, res) => {
try {
const userId = req.body.id;
console.log("Req"+userId);
const deletePlayer = await UserModel.destroy({
where:{ id : userId }
})
res.status(200).json({ deletePlayer });
} catch (e) {
res.status(500).json({ fail: e.message });
}
});

假设删除的记录实际上是定义为Home.js组件一部分的searchResults状态的一部分,则需要在Axios.delete请求成功后更新状态。这可以通过过滤(使用Array.filter(与id不匹配的其他结果来完成。

我不确定searchResults的确切结构,但我假设id,这是传递给onDelete方法的参数,是searchResults数组中每个对象的唯一属性之一。

const onDelete = id => () => {
try {
Axios.delete('http://localhost:8000/service/player', {
headers: {
'Content-Type': 'application/json'
},
data: {
'id' : id
}
});
setDeleteDialog(false);
const remainingResults = searchResults.filter((result) => result.id !== id)
setSearchResults(remainingResults);
} catch (e) {
console.log(e);
}
}

相关内容

  • 没有找到相关文章

最新更新