antd Select進階功能 動態更新、函式防抖
Antd Select
自帶的搜尋功能很多時候需要結合後端的介面,輸入一個關鍵字的時候會自動更新選擇器的選項. 下面列一些注意點
基礎實現
選擇器選項必須和每次更新的資料掛鉤, 這個值可以通過 state
,也可以通過 props
拿到
再結合迴圈的方法例如 map
遍歷渲染options
import 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( <Select mode="multiple"//多選模式 placeholder="請選擇" filterOption={false}//關閉自動篩選 onSearch={this.handleSearch} > { list.map((item, index) => ( <Option key={index} value={item}>{item}</Option> )) } </Select> ) } ... }
上面就是一個簡單的例子. 除了要動態渲染 Options
以外, 還需要注意設定這個屬性:
filterOption={false}
如果不設定會導致即使拿到了最新的資料還是依舊顯示無匹配結果
因為 filterOption
預設為true, 當你輸入內容時候,會先在已有選項裡面尋找符合項, 無論是否找到,都會重新渲染 Options
,這樣你介面請求的資料的渲染被覆蓋了, 自然看不到結果了。所以需要把它關掉!
二、函式防抖
效能優化
因為輸入是屬於高頻js的操作, 所以我們需要使用到函式節流或者函式防抖.
這裡我直接使用函式防抖外掛: lodash/debounce
import 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已經給我們封裝好了載入狀態的元件: <Spin />
.然後通過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( <Select ... notFoundContent={spinState ? <Spin /> : '暫無資料'} onSearch={this.handleSearch} ... > { list.map((item, index) => ( <Option key={index} value={item}>{item}</Option> )) } </Select> ) } }
更多的可以檢視官方文件: ofollow,noindex">《Antd-Select》