0

我正在发出两个 api GET 请求,并且我希望更新状态。由于某种原因,它仅使用第一个 GET 请求中的值进行更新。

我尝试使用扩展运算符更新状态并将新值添加到来自 GET 请求的当前状态(类别)。

axios // first get request
  .get(
    "LINK_TO_API"
  )
  .then(res => {
    this.setState({
      ...this.state.categories,
      categories: res.data.data
    });
  })
  .catch(function(error) {
    console.log(error);
  });
axios // second get request
  .get(
    "LINK_TO_API"
  )
  .then(res => {
    this.setState({
      ...this.state.categories,
      categories: res.data.data
    });
  })
  .catch(function(error) {
    console.log(error);
  });

我目前从第一个 GET 请求中获得 10 个值,并且希望在映射类别时获得总共 20 个值。

4

3 回答 3

1

您永远不会得到 20 个值,因为没有附加值,您只是在每次调用中覆盖类别值。

this.setState({
  ...this.state.categories,
  categories: res.data.data
});

这里categories: res.data.data正在被覆盖。

只需将您的代码修改为:

 axios
  .get(
    "LINK_TO_API"
  )
  .then(res => {
    this.setState((state) => ({
      ...state,
      categories: [...state.categories, ...res.data.data]
    }));
  })
  .catch(function(error) {
    console.log(error);
  });
于 2019-04-22T08:22:13.943 回答
0

假设 categories 是一个array,你正在用另一个数组覆盖一个数组。

在下面的代码中,我总是返回一个新数组,并将新数组与前一个数组连接起来。

axios // first get request
  .get('LINK_TO_API')
  .then(res => {
    this.setState({
      categories: [...this.state.categories, ...res.data.data]
    });
  })
  .catch(function(error) {
    console.log(error);
  });
axios // second get request
  .get('LINK_TO_API')
  .then(res => {
    this.setState({
      categories: [...this.state.categories, ...res.data.data]
    });
  })
  .catch(function(error) {
    console.log(error);
  });
于 2019-04-22T08:20:27.147 回答
0

首先,您的扩展运算符是错误的,您必须将其包装成 array categories: [...this.state.categories, ...res.data.data]。另外我建议您等待所有帖子加载,然后将它们设置为状态:

Promise.all([axios.get('LINK_TO_API'), axios.get('LINK_TO_API_2')])
    .then(allYourPosts => {
        this.setState({ /* set it to state */ });
    })
    .catch((error) => {
        console.log(error);
    });
于 2019-04-22T08:24:25.330 回答