我正在使用react-admin并尝试创建一个带有自动完成字段的过滤器,该过滤器将在我键入时进行查询,并且仅当搜索条件长度长于2时才开始发送查询。
我目前正在使用shouldRenderSuggestions
在我的里面AutocompleteInput
字段,但这仍然发送两个在“昵称”过滤器中带有空字符串的请求,这是代码部分:
<AutocompleteInput optionText="nickname" shouldRenderSuggestions={(val) => {
return val.trim().length > 2
}}/>
发生的事情是当我填写第一个和第二个字母时GET
请求已发送,但其中包含空字符串nickname
field,
输入的字符串例如:“abc”:
第一个请求:http://website.loc/clients?filter={"nickname":""}&page=1&perPage=25&range=[0,24]&sort=["id","DESC"]
第二个请求:http://website.loc/clients?filter={"nickname":""}&page=1&perPage=25&range=[0,24]&sort=["id","DESC"]
第三个请求:http://website.loc/clients?filter={"nickname":"abc"}&page=1&perPage=25&range=[0,24]&sort=["id","DESC"]
我想完全避免发送前两个请求。
组件完整代码:
const PostPagination = props => (
<Pagination rowsPerPageOptions={[]} {...props} />
);
const PostFilter = (props) => (
<Filter {...props}>
<ReferenceInput label="Client"
source="client_id"
reference="clients"
allowEmpty
filterToQuery={searchText => ({ nickname: searchText })}>
<AutocompleteInput optionText="nickname" shouldRenderSuggestions={(val) => {
return val.trim().length > 2
}}/>
</ReferenceInput>
</Filter>
);
const PostsList = props => {
return (
<List {...props} perPage={15}
pagination={<PostPagination/>}
filters={<PostFilter/>}
exporter={false}>
<Datagrid>
<TextField source="nickname" sortable={false}/>
<DateField label="Created" source="created_at" showTime/>
</Datagrid>
</List>
);
};
Edit:同样的问题也适用于“输入时搜索”字段,例如<TextInput>
在 Filter>领域,我开始问一个新问题,但意识到这会有点重复,
该代码还发送从 1 个字符开始的请求,在本例中甚至没有shouldRenderSuggestions
强制其发送空请求的选项
const ClientFilter = (props) => (
<Filter {...props}>
<TextInput label="Search" source="str" alwaysOn/>
</Filter>
);
codesandbox.io 中的实时代码示例 https://k2r9p6r18r.codesandbox.io/#/posts/create