【问题标题】:Using a function to get API data and populate a provider [closed]使用函数获取 API 数据并填充提供程序 [关闭]
【发布时间】:2020-01-30 20:10:38
【问题描述】:

我尝试使用函数从 API 获取数据,然后在我的 React 提供程序中设置状态。

如果我像这样直接在componentDidMount 中这样做,效果很好:

componentDidMount() {
axios({
  method: "post",
  url: "https://example.com",
  // data: formData,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  }
}).then(res => {
  this.setState({
    TabPass: res.data
  });
});
    }

我试图获得相同的结果,但将 axios 放入一个单独的文件中,一旦获得数据,我就会在我的提供程序中执行 setState。

我在 api.js 中试过这个

export function GetPass ()
{
    axios({
        method: "post",
        url: https://example.com",
        // data: formData,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
        }
      })
        .then(res => {
            return res.data;
        }
        )
}

在 Provider.js 中

  componentDidMount() {

    const Tab = GetPass();
      this.setState({
        TabPass:Tab,
      })
    }
  }

标签未定义

【问题讨论】:

  • 请发布不适合您的代码,以便我们指出需要修复的地方。
  • 这是因为你没有等待调用完成,你的axios请求是异步的
  • 我知道我不知道的是,当我使用 setState 时,如何使用单独的函数等待调用完成
  • 标签仍未定义

标签: reactjs function fetch


【解决方案1】:

在 api.js 中

export function GetPass ()
{
    //Following will return a promise with the data once resolved
    return axios({
        method: "post",
        url: https://example.com",
        // data: formData,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
        }
      })
        .then(res => {
            return res.data;
        }
        )
}

在 Provider.js 中

componentDidMount() {
    // As the axios promise will resolved your state will change
    GetPass()
      .then(Tab => { this.setState({
        TabPass: Tab,
      }))
    }}

【讨论】:

  • 感谢您的回答。在提供者选项卡现在是一个承诺,但我没有结果(对不起,我不是反应专家:))
  • 尝试遵循``` const Tab = GetPass().then(data => ```
  • 我想将答案标记为正确,但正如我在之前的评论中告诉你的那样,我的 const 不是结果而是一个承诺(使用 PromiseStatus 和 PromiseValue)。如何访问结果?
  • 我已经更新了上面的答案。如果仍然有问题,请检查并恢复:)
  • 正是我需要的。非常感谢
猜你喜欢
  • 2014-10-10
  • 1970-01-01
  • 2021-02-24
  • 2022-01-01
  • 1970-01-01
  • 2018-07-01
  • 2014-04-28
  • 2017-10-06
  • 1970-01-01
相关资源
最近更新 更多