Javascript 获取后如何更新数据?
我正在fetchData方法中获取componentDidMount上的数据。之后,我尝试使用该方法删除数据。我试图在deleteUser方法中立即更新日期,但它不起作用。使用delete方法获取数据后,如何更新此数据Javascript 获取后如何更新数据?,javascript,reactjs,api,fetch,Javascript,Reactjs,Api,Fetch,我正在fetchData方法中获取componentDidMount上的数据。之后,我尝试使用该方法删除数据。我试图在deleteUser方法中立即更新日期,但它不起作用。使用delete方法获取数据后,如何更新此数据 fetchData = () => { let url = `https://contact-browser.herokuapp.com/contacts`; fetch(url, {method: 'get'}).then(resp => resp.
fetchData = () => {
let url = `https://contact-browser.herokuapp.com/contacts`;
fetch(url, {method: 'get'}).then(resp => resp.json()).then((data) =>
this.setState({
data: Object.entries(data).map(([key,value])=>({key:Number(key),value}))
})
);
};
componentDidMount() {
this.fetchData();
}
deleteUser = (id) => {
let url = `https://contact-browser.herokuapp.com/contact/${id}`;
fetch(url, {method: 'delete'}).then(resp => console.log(resp));
this.fetchData();
};
完成删除提取后重新提取数据,这可确保在服务器上完全解析删除后提取数据
deleteUser = (id) => {
let url = `https://contact-browser.herokuapp.com/contact/${id}`;
fetch(url, {method: 'delete'}).then(resp => {
this.fetchData();
});
};
由于JS的异步行为,它“不起作用”。
简单地说,当代码中有任何等待(如DB调用、API调用等)时,JS代码允许该特定代码运行并开始执行下一行
在本例中,由于fetch是一个i/o等待,因此控件移动到下一行-this.fetchData()
。因此,fetchData()
在实际发生删除之前被调用
下面是另一个使用async和await的解决方案
您还可以使用async和Wait
deleteUser = async (id) => {
let url = `https://contact-browser.herokuapp.com/contact/${id}`;
const deleted = await fetch(url, {method: 'delete'}).then(resp => console.log(resp));
if(deleted){
await this.fetchData();
}
};
当你说“它不工作”时,会发生什么,而不是你希望发生什么?它会删除用户,但数据是相同的。
deleteUser = async (id) => {
let url = `https://contact-browser.herokuapp.com/contact/${id}`;
const deleted = await fetch(url, {method: 'delete'}).then(resp => console.log(resp));
if(deleted){
await this.fetchData();
}
};