【问题标题】:React JS fetch data from multiple API functionReact JS 从多个 API 函数中获取数据
【发布时间】:2021-05-24 07:23:27
【问题描述】:

我的任务是为 poc 创建一个前端。我不是前端开发人员,但我选择使用 React JS。 只有一个页面从多个 API 端点获取数据。 API 端点返回一个简单的 json 对象。 我设法让它工作,但是我的代码很难看,我想创建一个函数来处理所有这些,但我似乎无法做到正确。这是我的代码

export default class Dashboard extends React.Component {

constructor(props) {
    super(props);
    this.state = {
      group1: [],
      group2: [],
      group3: [],
      isLoaded: false,
    }
  }

componentDidMount() {
    const group1_url = "http://localhost/api/1"
    const group2_url = "http://localhost/api/2"
    const group3_url = "http://localhost/api/3"

    fetch(group1_url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          group1: json,
        })
      });
    fetch(group2_url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          group2: json,
        })
      });
    fetch(group3_url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          group3: json,
        })
      });
  }

我正在尝试创建这样的函数:

 function fetch_data(url, state) {
    fetch(url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          state: json,
        })
      });
  }

var group1 = fetch_data(group1_url, group1);

到目前为止还没有快乐。如何创建一个函数来获取数据并在 js 中设置状态? 或者,我怎样才能让我的代码看起来更好?或者还有什么我应该使用/研究的东西吗?

【问题讨论】:

    标签: reactjs rest fetch-api


    【解决方案1】:

    传递一个字符串作为第二个参数,并使用计算属性:

    function fetch_data(url, state) {
        fetch(url)
          .then(res => res.json())
          .then(json => {
            this.setState({
              [state]: json,
            })
          });
      }
    
    fetch_data(group1_url, 'group1');
    

    我还强烈建议捕获错误 - 应尽可能避免可能的未处理拒绝。

    您可能希望使用Promise.all 等待所有组加载:

    const dataSources = {
        group1: 'http://localhost/api/1',
        group2: 'http://localhost/api/2',
        group3: 'http://localhost/api/3',
    };
    
    Promise.all(
        Object.entries(dataSources).map(([propertyName, url]) => (
            fetch(url)
                .then(res => res.json())
                .then((result) => {
                    this.setState({
                        [propertyName]: result
                    })
                })
        ))
    )
        .then(() => {
            this.setState({ isLoaded: true })
        })
        .catch((error) => {
            // handle errors
        })
    

    (另请注意your json argument is not a JSON - JSON 只是一种与 strings 一起存在的格式。已经反序列化的东西只是一个普通的对象或数组。最好把它称为不那么误导的东西,比如result 和我一样)

    【讨论】:

    • 非常感谢,我在我的代码中使用了您的实现,它立即生效。现在干净多了。我也添加了错误处理。
    【解决方案2】:

    你可以试试Promise.all

    Promise.all 接受一个 Promise 数组(从技术上讲,它可以是任何可迭代的,但通常是一个数组)并返回一个新的 Promise。

    const points = [
        "http://localhost/api/1",
        "http://localhost/api/2",
        "http://localhost/api/3",
    ];
    
    const responses = await Promise.all(points.map((point) => fetch(point)));
    const data = await Promise.all(responses.map((response) => response.json()));
    const [group1, group2, group3] = data;
    
    this.setState({
        group1,
        group2,
        group3,
    });
    

    请记住将此逻辑包装在 async 函数中

    【讨论】:

      【解决方案3】:

      你可以这样做。

      function fetch_data(url, state) {
      fetch(url)
        .then(res => res.json())
        .then(json => {
          this.setState({
            [state]: json,
          })
        });
      }
      
      var group1 = fetch_data(group1_url, 'group1');
      

      【讨论】:

        猜你喜欢
        • 2021-11-09
        • 1970-01-01
        • 1970-01-01
        • 2021-02-12
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 1970-01-01
        • 2021-09-27
        相关资源
        最近更新 更多