【问题标题】:fetching json in seperate component在单独的组件中获取 json
【发布时间】:2019-02-26 18:25:44
【问题描述】:

我已经创建了一个应用程序,并且想添加更多组件,这些组件将使用我在“personlist.js”中获取的相同 json,所以我不想在每个应用程序中都使用 fetch(),我想做一个只做fetch的单独组件,在其他组件中调用它,然后在每个组件中映射函数,如何使只获取组件?

这是我的获取方法:

componentDidMount() {
    fetch("data.json")
      .then(res => res.json())
      .then(
        result => {
          this.setState({
            isLoaded: true,
            items: result.results
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

这是一个沙盒 sn-p https://codesandbox.io/s/1437lxk433?fontsize=14&moduleview=1

【问题讨论】:

  • 您可以(并且应该:-))在此处现场制作可运行的示例,这样您就不会意外遗漏重要代码。 Stack Snippets 支持 React,包括 JSX; here's how to do one。 (他们也应该是minimal。)

标签: javascript json reactjs web-applications jsx


【解决方案1】:

我不明白为什么这需要成为一个组件,而只是一个其他组件使用的功能。

但是,如果您希望它成为其他组件使用的组件,请让它们将映射函数传递给它以用作道具,然后在您取回项目时在componentDidMount 中使用它,并渲染映射的项目在render


在您已澄清的评论中:

我试图获取 json 一次,但我不确定最好的方法是什么。

在那种情况下,我不会使用组件。我将调用放在一个模块中,并让模块公开承诺:

export default const dataPromise = fetch("data.json")
    .then(res => {
        if (!res.ok) {
            throw new Error("HTTP status " + res.status);
        }
        return res.json();
    });

使用 Promise 的代码会这样做:

import dataPromise from "./the-module.js";
// ...
componentDidMount() {
    dataPromise.then(
        data => {
            // ...use the data...
        },
        error => {
            // ...set error state...
        }
    );
}

数据在模块加载时获取一次,然后每个组件都可以使用它。模块将数据视为只读,这一点很重要。 (您可能希望模块导出一个创建防御性副本的函数。)

【讨论】:

  • 我正在尝试获取 json 一次,但我不确定最好的方法是什么。
  • 您好@t-j-crowder,我在stackoverflow.com/questions/54917627/… 上有一个问题,如果您能对此发表评论,将会非常有帮助,谢谢!
【解决方案2】:

不确定这是否是您正在寻找的答案。

fetchDataFunc.js

export default () => fetch("data.json").then(res => res.json())

组件.js

import fetchDataFunc from './fetchDataFunc.'

class Component {
  state = {
    // Whatever that state is
  }

  componentDidMount() {
    fetchFunc()
      .then(res => setState({ 
        // whatever state you want to set
      }) 
      .catch(err => // handle error)
  }
}

Component2.js

import fetchDataFunc from './fetchDataFunc.'

class Component2 {
  state = {
    // Whatever that state is
  }

  componentDidMount() {
    fetchFunc()
      .then(res => setState({ 
        // whatever state you want to set
      }) 
      .catch(err => // handle error)
  }
}

您还可以有一个 HOC,它只获取一次数据并在不同组件之间共享。

【讨论】:

  • 我已经使用 fetchDataFunc.js 完成了它并且它提取了两次,你能告诉我如何像你提到的那样在父子中提取一次吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2021-11-25
  • 1970-01-01
  • 2011-12-26
  • 2021-05-22
  • 2021-03-24
  • 2017-01-13
相关资源
最近更新 更多