[英]Update State after `axios.post()`
使用 Express 框架修改 MongoDB,我可以将文档添加到名为faculties
的集合中。 此外,下拉框显示 collection faculties
文档的属性name
,当我可以在 post 方法完成后检查它。 但是,当我通过状态并从中检索faculties
集合时: const { faculties } = state;
然后检查 collection faculties
文档数组的属性name
,它没有显示数据库中的最新添加。 (我正在寻找名为exampleFaculty
的新插入的faculty
文档的属性“id”以实现多对多关系)。
forceUpdate()
来更新状态,但是据我forceUpdate()
,这会更新render
而不是状态。 尽管如此,渲染已更新,但状态未更新。 这是实现:this.forceUpdate();
axios.post('http://localhost:3001/api/putFaculty', {name: message});
this.forceUpdate();
ManyToManyDbMain.Main(message,collectionName,this.state) // implement many to many relationships in db
this.setState(this.state);
更新状态:this.forceUpdate();
axios.post('http://localhost:3001/api/putFaculty', {name: message});
this.forceUpdate();
this.setState(this.state);
ManyToManyDbMain.Main(message,collectionName,this.state) // implement many to many relationships in db
this.forceUpdate();
axios.post('http://localhost:3001/api/putFaculty', {name: message});
this.forceUpdate();
this.getFaculties()
this.setState(this.state);
ManyToManyDbMain.Main(message,collectionName,this.state) // implement many to many relationships in db
其中 fetch 方法包括:
// read the mongodb collection faculties in database "education"
getFaculties= () => {
fetch('http://localhost:3001/api/getFaculties')
.then((data) => data.json())
//set property "faculties" within the state" (won't throw error if you haven't defined property "faculties" within state".
.then((res) => this.setState({ faculties: res.data }));
};
axiom.post(..)
方法的响应axiom.post(..)
读取新功能:axios.post('http://localhost:3001/api/putFaculty', {name: message})
.then(response => {
const {faculties} = this.state;
alert(response.data)
alert(response.name)
faculties.push(response.data);
this.setState({faculties});
})
但这会返回一个object Object
并且我还不知道如何读取该对象的属性,我尝试将其映射到.name
属性中: response.map((dat) => dat.name)
但响应没有名为map
函数。
this.getFaculties();
if (!this.state.intervalIsSet) {
let interval = setInterval(this.getFaculties, 1000);
this.setState({ intervalIsSet: interval });
}
ManyToManyDbMain.Main()
方法之前自动更新状态。 相反,在代码继续之前,网站/代码会冻结 7 秒(意味着状态也不会更新)。如何在axios.post()
之后更新状态,以便最新的收集faculties
文档包含在传递给ManyToManyDbMain.Main(..)
?
以下对 xy 问题的解决方案已被确认但不会被说服。
App.js
有 Id。 但是,在 DB 中实现多对多关系的原因是因为它被设计为许多用户(可能)使用的小型数据库,因此我想减少计算时间(应用搜索查询来查找子集 ID)以更大的数据库为代价。 这也意味着我不想在网站中创建一个单独的系统来管理所有创建的 Id 并在 MongoDb 已经有一个优化的 Id 分配系统时防止双重 Id。您可以使用axios
() 方法来设置组件的状态。
例如 -
axios.get('http://localhost:3001/api/getFaculties')
.then(res => {
/** Console here to get an actual response from server */
console.log(res);
this.setState({
faculties: res.data.results
});
})
.catch(function(error) {
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.