React JS 从多个 API 函数中获取数据

React JS fetch data from multiple API function

我的任务是为一个 poc 创建一个前端。我不是前端开发人员,但我选择使用 React JS。 只有一页从多个 API 端点获取数据。 API 端点 return 一个简单的 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 中设置状态? 或者我怎样才能让我的代码看起来更好?或者还有什么我应该 use/look 进入的吗?

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

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)

你可以这样做。

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

var group1 = fetch_data(group1_url, 'group1');

你可以试试Promise.all

Promise.all takes an array of promises (it technically can be any iterable, but is usually an array) and returns a new 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 函数中