【问题标题】:Axios post is not working inside react useeffectAxios 帖子在反应使用效果中不起作用
【发布时间】:2021-09-10 19:47:10
【问题描述】:

我正在实现一个跟踪用户活动的 React 应用程序。而且我有一个名为 count 的变量,每次它发生变化时,我都必须使用我的 api 将它发布到我的 mongo 并做出反应。 但是 axios 帖子在 useeffect 中不起作用。而且我没有特定的用户驱动事件来激发像 handlesubmit 这样的帖子。 这是我的代码:

import React, { Component, useState, useEffect } from 'react';
import axios from 'axios';

const RealCount = () => {
    const [count, setCount] = useState();

    useEffect(() => {
      chrome.storage.local.get("count", function(results) {
          setCount(results.count);
        });
      const newCount = {
        name: "axfg",
        count: count
      }
      axios.post("http://localhost:3000/create", newCount)
        .then(response => {
          console.log(response);
          console.log(response.data);
        })
        .catch(error => {
          console.log(error);
        });
}

但是我在另一个组件的另一个函数中检查了我的 axios 帖子,它运行良好。 对此有何想法?

【问题讨论】:

    标签: reactjs api axios frontend use-effect


    【解决方案1】:

    这样的?

    import React, { Component, useState, useEffect } from 'react';
    import axios from 'axios';
    
    const RealCount = () => {
        const [count, setCount] = useState();
    
        useEffect(() => {
          chrome.storage.local.get("count", function(results) {
              setCount(results.count);
            });
          const newCount = {
            name: "axfg",
            count: count
          }
          (axios.post("http://localhost:3000/create", newCount)
            .then(response => {
              console.log(response);
              console.log(response.data);
            })
            .catch(error => {
              console.log(error);
            }))();
        }, [count]);
    }
    

    【讨论】:

    • 不,我之前试过了,也没用。
    • 我已经在 IIFE 中更新并包装了 axios 调用。你现在可以检查吗?
    • 它正在工作 Shravan。我犯了一个严重的错误,我没有在我的 App.js 中使用真正的计数组件。我在另一个组件中有此代码的副本,我正在使用它。我刚刚在尝试在此组件中创建按钮时发现了它。
    • 感谢您抽出宝贵时间帮助我。
    【解决方案2】:

    问题已解决 伙计们,这是我的错。我什至没有在我的 App.js 中使用这个组件。我在另一个组件中使用了此代码的副本。这就是为什么这些更改没有反映在我的程序中。

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 2019-01-26
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2020-05-31
      相关资源
      最近更新 更多