一、动态更新Options
Antd Select自带的搜索功能很多时候需要结合后端的接口,输入一个关键字的时候会自动更新选择器的选项. 下面列一些注意点
基础实现
选择器选项必须和每次更新的数据挂钩, 这个值可以通过state,也可以通过props拿到
再结合循环的方法例如map遍历渲染optionsimport React, { PureComponent, Fragment } from 'react'import { Select } from 'antd'import axios from 'axios'const Option = Select.Option;export default class AntSelect extends PureComponent{
...
handleSearch = (keywords) => { //请求后端搜索接口
axios('http://xxx.com/xxx', {
keywords,
}).then(data){ this.setState({ list: data
})
}
}
render(){ const { list } = this.state; return(
mode="multiple" //多选模式 placeholder="请选择"
filterOption={false} //关闭自动筛选 onSearch={this.handleSearch}
>
{
list.map((item, index) => ( {item}
))
}
)
}
...
}
上面就是一个简单的例子. 除了要动态渲染Options以外, 还需要注意设置这个属性:
filterOption={false}
如果不设置会导致即使拿到了最新的数据还是依旧显示无匹配结果
因为filterOption默认为true, 当你输入内容时候,会先在已有选项里面寻找符合项, 无论是否找到,都会重新渲染Options,这样你接口请求的数据的渲染被覆盖了, 自然看不到结果了。所以需要把它关掉!
二、函数防抖
性能优化
因为输入是属于高频js的操作, 所以我们需要使用到函数节流或者函数防抖.
这里我直接使用函数防抖插件:lodash/debounceimport debounce from 'lodash/debounce';//在constructor统一绑定事件. 和经常使用的bind(this)一样class AntSelect extends React.Component {
constructor(props) { super(props);
this.handleSearch = debounce(this.handleSearch, 500);
}
handleSearch = (value) => {
...
}
...
}
这样你在输入数据的500ms后才会触发handleSearch函数,可以大幅度减少调取后台接口的次数!
出现加载状态
antd已经给我们封装好了加载状态的组件:.然后通过state控制其出现和消失class antdSelect extends React.Component { constructor(props) { super(props);
this.state = { spinState: false,
}
}
handleSearch = (keywords) => {
... //调用接口前清空数据, 出现加载icon
this.setState({ list: [], spinState: true
})
//请求后端搜索接口
axios('http://xxx.com/xxx', {
keywords,
}).then(data){ this.setState({ list: data, spinState: false
})
}
...
}
render(){ const { list, spinState } = this.state; return(
...
notFoundContent={spinState ? : '暂无数据'}
onSearch={this.handleSearch}
...
>
{
list.map((item, index) => ( {item}
))
}
)
}
}