【问题标题】:Update State after `axios.post()`在 `axios.post()` 之后更新状态
【发布时间】:2019-12-30 12:49:34
【问题描述】:

场景

使用 Express 框架修改 MongoDB 我可以将文档添加到名为 faculties 的集合中。此外,显示集合faculties 中文档的属性name 的下拉框,当我可以在post 方法完成后检查它时。但是,当我通过状态并从中检索faculties 集合时,使用:const { faculties } = state;,然后检查集合faculties 的文档数组的属性name,它没有显示最新添加到数据库。 (我正在寻找新插入的名为 exampleFaculty 的文档的属性 'id' 以实现多对多关系)。

尝试

  1. 我尝试应用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
  1. 我试过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
  1. 我试过直接调用fetch方法更新状态:
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 })); 
    };
  1. 使用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 的函数.

  1. 由于状态每秒自动更新一次:
this.getFaculties();
        if (!this.state.intervalIsSet) {
            let interval = setInterval(this.getFaculties, 1000);
            this.setState({ intervalIsSet: interval });
        }
  1. 我尝试添加一个 5 秒的睡眠方法,并错误地期望状态会在状态传递给 ManyToManyDbMain.Main() 方法之前自动更新。相反,在代码继续之前,网站/代码会冻结 7 秒(意味着状态也不会更新)。

问题

如何更新axios.post()之后的状态,使faculties集合的最新文档包含在传递给ManyToManyDbMain.Main(..)的状态中?

忽略的快捷方式/XY 问题解决方案:

以下 xy 问题的解决方案得到认可但未被说服。

  1. 我可以手动生成所有文档的所有 ID,然后将它们推送到数据库中,这样我就可以在需要时将 ID 放在 App.js 中。但是,在数据库中实现多对多关系的原因是因为它被设计为许多用户(可能)使用的小型数据库,因此我想减少计算时间(应用搜索查询来查找子集 id)以更大的数据库为代价。这也意味着我不想在网站中创建一个单独的系统来管理所有创建的 Id 并在 MongoDb 已经具有优化的 Id 分配系统时防止双重 Id。
  2. 我可以每 n 毫秒添加一个第二个循环,检查是否某个布尔值指示是否添加了新教师,并从那里启动“获取 Id 方法”。但我认为这会使代码变得不必要地复杂、难以测试、可能对多个用户不可靠以及计算密集型,我正在努力避免这种情况。

【问题讨论】:

    标签: javascript mongodb express axios state


    【解决方案1】:

    您可以使用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);
      });
    

    【讨论】:

    • 感谢您的努力和快速响应,您的解决方案将dat.facultyName={faculties.map((dat) => dat.name)} 与TypeError: Cannot read property 'map' of undefined 分开,因为它似乎与我在尝试3 中指定的fetch 实现不兼容。包括.then((data) => data.json())并禁用您的catch 方法,它会在Unhandled Rejection (TypeError): data.json is not a function 上中断。启用catch 方法后,它不再显示任何状态,它变得未定义。我怎样才能将教师姓名exampleFaculty 传递给您的axiom.get?
    • axios.get(`localhost:3001/api/getFaculties/${faculty_name})
    • 根据您的评论,您获取的数据格式不正确(不是对象数组)。您需要检查服务器响应。这就是为什么我在代码 /** Console here 中添加注释以获得来自服务器的实际响应 */
    • 我假设您的意思是 axios.get('http://localhost:3001/api/getFaculties$faculty_name') 在调用 axios.get(..) 之前定义了一个变量 var faculty_name = "exampleFaculty";。
    • 您可以在此处使用字符串文字。比如${serverURL}users/${userData.id}。关注此以了解更多信息 - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 2021-09-16
    • 2023-01-28
    • 2018-01-25
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2020-08-04
    • 2016-08-26
    • 2016-10-02
    相关资源
    最近更新 更多