如何解决获取请求未更新状态
我有一个连接到数据库的 React 应用程序。目前,应用程序在装载时获取数据库并使用它来填充状态。这些应用程序允许某人发布到数据库。到目前为止,这是有效的。
问题是我希望用户看到新发布的内容。因为它是内容仅在我重新加载页面后才会填充。我尝试在 POST 请求后运行的函数中重复 componentDidMount() 中的编码,但由于某种原因不起作用。
class App extends Component {
state = {
notes: [],folders: [],//noteID: 0,//folderID: 0
};
componentDidMount() {
Promise.all([
fetch(`${config.API_ENDPOINT}/notes`),fetch(`${config.API_ENDPOINT}/folders`)
])
.then(([notesRes,foldersRes]) => {
if (!notesRes.ok)
return notesRes.json().then(e => Promise.reject(e))
if (!foldersRes.ok)
return foldersRes.json().then(e => Promise.reject(e))
return Promise.all([
notesRes.json(),foldersRes.json(),])
})
.then(([notes,folders]) => {
this.setState({ notes,folders })
})
.catch(error => {
console.error({ error })
})
}
pageReload = () =>{
//console.log('pageReload ran');
Promise.all([
fetch(`${config.API_ENDPOINT}/notes`),fetch(`${config.API_ENDPOINT}/folders`)
])
.then(([notesRes,foldersRes]) => {
if (!notesRes.ok)
return notesRes.json().then(e => Promise.reject(e))
if (!foldersRes.ok)
return foldersRes.json().then(e => Promise.reject(e))
return Promise.all([
notesRes.json(),])
})
.then(([notes,folders]) => {
this.setState({ notes,folders })
})
.catch(error => {
console.error({ error })
})
}
folderSubmit = (f) => {
//console.log("folderSubmit ran " + f);
const newFolder = { "name" : f };
const postfolder = {
method: 'POST',headers: {
'content-type': 'application/json'
},body: JSON.stringify(newFolder)
};
fetch(`${config.API_ENDPOINT}/folders`,postfolder).then(this.pageReload())
}
解决方法
看起来您在发布后没有设置状态。请参阅下面需要设置状态的位置。
folderSubmit = (f) => {
//console.log("folderSubmit ran " + f);
const newFolder = { "name" : f };
const postfolder = {
method: 'POST',headers: {
'content-type': 'application/json'
},body: JSON.stringify(newFolder)
};
fetch(`${config.API_ENDPOINT}/folders`,postfolder)
.then(response => response.json())
.then(data => this.setState(data));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。