javascript 如何在reactJs中获取API

rjzwgtxy  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(112)

请建议一种方法来获取API,而不是从DATA文件夹导入JSON文件。

我试图获取一些数据(API)作为我的过滤多选组件中的选项。非常新的React,请建议。

import React, { Component } from 'react'
   import FilteredMultiSelect from 'react-filtered-multiselect';
   import axios from 'axios';

class SlideOne extends Component  {
     
    constructor() {
        super()
        this.state = {
          selectedOptions: [],
        }
      }
    componentDidMount(){
        axios.get("https://api.myjson.com/bins/xcfy7/")
         .then((response)=>{
          this.setState(()=>{
                   return {
                     selectedOptions: response.data.tax
                   }
          })
         })     
    }
     
    handleDeselect = (deselectedOptions) => {
        var selectedOptions = this.state.selectedOptions.slice()
        deselectedOptions.forEach(option => {
          selectedOptions.splice(selectedOptions.indexOf(option), 1)
        })
        this.setState({selectedOptions})
    }
    
    handleSelect = (selectedOptions) => {
    
        selectedOptions.sort((a, b) => a.taxId - b.taxId)
        this.setState({selectedOptions})
    }
      
    render() {
        
     
      return (
    
          <div className="row">   
           <div className="col-md-6">
            <FilteredMultiSelect
              placeholder="Select from here"
              buttonText="Add"
              classNames={{
                filter: 'form-control',            
                select: 'form-control',
                button: 'btn btn btn-block btn-default',           
                buttonActive: 'btn btn btn-block btn-primary'
              }}
              onChange={this.handleSelect}
              options={this.state.selectedOptions}
              selectedOptions={this.state.selectedOptions}
              textProp="taxName"
              valueProp="taxId"
            />
          </div>      
          <div className="col-md-6">
             <FilteredMultiSelect
              placeholder="get selected here"
              buttonText="delete"
              classNames={{
    
                filter: 'form-control',            
                select: 'form-control',            
                button: 'btn btn btn-block btn-default',            
                buttonActive: 'btn btn btn-block btn-danger'
              
              }}
    
              onChange={this.handleDeselect}
              options={this.state.selectedOptions}
              textProp="taxName"
              valueProp="taxId"
            />
    
           
          </div>
        </div>)
        
    }}
   
    export default SlideOne;`

字符串

cqoc49vn

cqoc49vn1#

您可以使用Axios调用远程API并获取数据。确保在componentDidMount()生命周期事件中包含数据获取,并使用获取的数据调用setState()来更新DOM。

相关问题