reactjs - 获取请求未更新状态
问题描述
我有一个连接到数据库的反应应用程序。目前,应用程序在挂载时获取数据库并使用它来填充状态。这些应用程序允许某人发布到数据库。到目前为止,这行得通。
问题是我希望用户看到新发布的内容。因为它是仅在我重新加载页面后才会填充的内容。我试图在 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(),
foldersRes.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));
}
推荐阅读
- influxdb - 在 TAG 上具有多个条件的 SELECT 语句
- vb.net - VB.Net中面板之间的字符串传递
- java - Spring Boot application shutting down immediately mentioning ApplicationContext
- javascript - 导航问题未定义不是对象(评估“_this2.props.navigation.navigate”)
- c# - 如何在 C# 中进行多重继承?
- html - 即使在 Firefox 和 Chrome 中添加显示 webkits 后,显示 flex 也无法工作
- javascript - 更新工具提示内容不会更新,因为它已经初始化?
- java - 我的 java(JFrame) 播放器移动脚本不起作用
- reactjs - 使用 userEvent、fireEvent 和常规点击之间的点击反应测试库差异
- c# - 在 Micorsoft bot 框架中使用 c# 和 v4 版本在聊天机器人中使用 Microsoft Bot Framework 设置计时器