场景
使用Express框架来修改MongoDB,我可以将文档添加到名为faculties的集合中。此外,当我可以在post方法完成后检查时,在集合name中显示文档属性faculties的下拉框。但是,当我传递状态,并使用:faculties从它检索const { faculties } = state;集合,然后检查集合faculties文档数组的属性name时,它将不会显示数据库中最近添加的内容。(我正在寻找新插入的名为faculty的exampleFaculty文档的属性'id‘,以实现多到多的关系)。
尝试
forceUpdate()来更新状态,但据我所知,这将更新render而不是状态。不过,呈现是更新的,但状态不是。这是implementation: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 dbthis.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 dbthis.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其中,提取方法包括:
// 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(..)方法的响应来读取新的设备: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,我还不知道如何读取该对象的属性,我尝试用:response.map((dat) => dat.name)将其映射到一个.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-问题解决方案:
以下xy问题的解决方案是公认的,但没有被说服.
App.js中了。然而,在DB中实现多对多关系的原因是,它被设计成一个小型数据库(可能被许多用户使用),因此我希望以更大的数据库为代价减少计算时间(应用搜索查询查找子集id)。这也意味着我不想在网站上创建一个单独的系统来管理所有创建的Id,并在MongoDb已经优化了Id分配系统的情况下阻止双Id。发布于 2019-12-30 13:01:11
可以使用axios .then()方法来设置组件的状态。
例如-
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);
});https://stackoverflow.com/questions/59531138
复制相似问题