简体   繁体   English

将接收到的数据从 api 格式化为数组 React Axios

[英]Formatting the received data from an api into an array React Axios

I am new to react and I have designed a drop-down menu using react-select我是新手,我使用 react-select 设计了一个下拉菜单

const Locations = [
  { label: "Albania", value: 355 },
  { label: "Argentina", value: 54 },
  { label: "Austria", value: 43 },
  { label: "Cocos Islands", value: 61 },
  { label: "Kuwait", value: 965 },
  { label: "Sweden", value: 46 },
  { label: "Venezuela", value: 58 }
];

<Select placeholder='Select from pre-created Tags 'onChange={handleDropDown('Tags')} defaultValue={values.Tags} required options={Locations}/>

and I have received some data drom an api using axios:我已经使用 axios 从 api 收到了一些数据:

 state = {
    locations:[],
    departments: [],
    tagsList:[],
  }

axios.get('/api/jobs/list-tags',{headers:headers}).then(respo =>{
      console.log(respo.data)
      this.setState({
        tagsList:respo.data
      })
      console.log(this.state.tagsList)

the data received from the api looks like this:从 api 收到的数据如下所示:

Object { id: 1, name: "MongoDB" }
Object { id: 2, name: "JavaScript" }

I want to replace the hardcoded data in Locations array with the info received from the api in the same format.我想用从 api 收到的相同格式的信息替换 Locations 数组中的硬编码数据。 (instead of { label: "Albania", value: 355 }, { id: 2, name: "JavaScript" } ). (而不是{ label: "Albania", value: 355 }, { id: 2, name: "JavaScript" } )。 how can I achieve this?我怎样才能做到这一点?

You can map the response data:您可以map响应数据:

      this.setState({
        locations: respo.data.map(t=>({label: t.name, value: t.id}))
      })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM