一种数据来自两种获取方法

时间:2019-04-05 07:11:23

标签: reactjs dictionary get axios

我有两个单独的axios get方法,可将响应数据映射到单独的数据对象。然后我在渲染中映射数据。我想将来自两个axios的数据放到一个对象中,以仅在渲染中映射一个对象。我该怎么办?

两个get函数之一

getData() {
  axios
    .get("http://localhost/GetAll?", {
      params: { rok: this.state.rok, idUchwaly: "1" },
      headers: { Authorization: "Bearer " + this.state.token }
    })
    .then(response =>
      response.data.map(data2 => ({
        IDA: `${data2.idZadania}`,
        idWersji: `${data2.idWersji}`,
        Dzial: `${data2.dzial}`
      }))
    )
    .then(data2 => {
      if (data2 == "") {
      } else {
        this.setState({ data2, isLoadingdane: true });
      }
    })
    .catch(error => this.setState({ error }));
}

然后将数据映射到表中

{this.state.isLoadingdane ? (
  data2.map(user2 => {
    const { IDA, idWersji, Dział } = user2;
    return (
      <tr id={IDA}>
        <td>
          <p>{idWersji}</p>
        </td>
        <td>
          <p>{Dzial}</p>
        </td>
      </tr>
    );
  })
) : (
  <tr>
    <td colSpan="3">
      <center>
        <p>Brak</p>
      </center>
    </td>
  </tr>
)}

我想要一个可以在其中放置两个值的表getp

类似这样的内容:{来自getData的值} {来自getData2的值}

2 个答案:

答案 0 :(得分:0)

代替直接将对axios请求的响应置于状态,您可以返回promise并等待两个请求都以Promise.all完成,然后将两个数组中的对象合并为一个数组。

示例

class App extends React.Component {
  componentDidMount() {
    Promise.all([this.getData(), this.getData2]).then(([data1, data2]) => {
      this.setState({
        data2: data1.map((item, index) => ({ ...item, ...data2[index] })),
        isLoadingdane: true
      });
    });
  }

  getData = () => {
    return axios
      .get("http://localhost/GetAll?", {
        params: { rok: this.state.rok, idUchwaly: "1" },
        headers: { Authorization: "Bearer " + this.state.token }
      })
      .then(response =>
        response.data.map(data2 => ({
          IDA: `${data2.idZadania}`,
          idWersji: `${data2.idWersji}`,
          Dzial: `${data2.dzial}`
        }))
      );
  };

  getData2 = () => {
    return axios.get(/* ... */);
    // ...
  };

  render() {
    // ...
  }
}

答案 1 :(得分:0)

Bartek,您需要这样映射结果:

const first = [{
  x: 'x',
  y: 'y',
}];

const second = [{
  x: 'x',
  z: 'z',
}];

const all = first.map(o => ({ ...o, ...second.find(f => f.x === o.x)}));

console.log(all);