首页 > 解决方案 > 映射 axios 响应,然后将其用于另一个响应

问题描述

我想映射一组图像,但因为 Directus 将图像或文件标识为集合项目中的 id。

现在我需要从第一个请求中的响应中映射 id 数组,然后使用该 id 在另一个端点发出另一个 get 请求,这就是文件。

我使用的数据库是DirectusCms,前端是react.js

class ComponentToPrint extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoad = this.handleLoad.bind(this);
      this.state = {
        nama: [],
        kk:[],
        ijazah:[]
    };
    }

    componentDidMount() {
        window.addEventListener('load', this.handleLoad);
    }

    componentWillUnmount() { 
      window.removeEventListener('load', this.handleLoad)  
    }
    
    handleLoad() {
      
      let nama_1;
      let id_kk;


      const url = `https://sensor/public/gemaclc/items/pendaftar?access_token=sensor`
      const url2 = `https://sensor/public/gemaclc/files/${id_kk}?access_token=sensor`
      

    axios(url, { 
        method: 'get', 
        headers:{ 'Content-Type': 'application/json'} })
        .then(res => {
            const nama = res.data.data;
            const nama = res.data.data;
            console.log( nama)
            this.setState( {nama} );
          })
    .catch(error => console.error('Error:', error))
    // .then(res => {console.log('Success:', nama)})

    // this.setState( nama );
    // console.log(nama)
    axios(url2,{
      method:`get`,
      headers:{ 'Content-Type': 'application/json'} })
        .then(res => {
            id_kk = res.data.data;
            console.log( id_kk)
            // this.setState( {id_kk} );
          })
        }

  render() {
    return (
      <>
    {this.state.nama.map(node => 
      <div key={node.id}>
      <h2>Nama :{node.nama}</h2>
      <h2>Tanggal lahir : {node.tanggal_lahir}</h2>
      <h2>Tempat lahir : {node.tempat_lahir}</h2>
      <h2>Email : {node.email}</h2>
      <h2>Email : {node.telepon}</h2>
      <h2>kk : {node.kartu_keluarga}</h2>
      </div>
      )}
       
      </>
    );
  }
}

标签: reactjsrequestaxiosdirectus

解决方案


当从itemsDirectus 中的端点请求时,可以提供一个名为 的查询参数fields,这样您就可以从关系中获取嵌套信息,包括哈希等,请参阅:https ://docs.directus.io/api/items.html#fields-可选的

如果你有private哈希,你可以使用assets端点来获取实际的图像,见:https ://docs.directus.io/api/assets.html#get-an-asset

PS:你没有提到你的问题是什么,所以我根据我对该主题的整体了解猜测它 - 下次还要提到你的确切问题,你尝试了什么,什么没用等


推荐阅读