请建议一种方法来获取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;`
字符串
1条答案
按热度按时间cqoc49vn1#
您可以使用Axios调用远程API并获取数据。确保在componentDidMount()生命周期事件中包含数据获取,并使用获取的数据调用
setState()
来更新DOM。