这是我当前使用以下代码的设计,可以正常工作。
如果我在搜索输入中输入文字,然后在下拉菜单中选择searchBy,然后单击搜索按钮,
搜索完成。
沙箱:
https://codesandbox.io/s/twilight-firefly-i4osi?file=/Search.js
例如使用jsonplaceholder,尽管jsonPlaceholder无法访问查询
Search.js
var globalSearchValue = ''
var globalSearchID = ''
function Search(props) {
const columns = [
{ key: 'id', numeric: false, disablePadding: false, label: 'id' },
{ key: 'fullName', numeric: false, disablePadding: false, label: 'Name' },
];
const searchableColumns = [
{ key: 'id', label: 'ID' },
{ key: 'fullName', label: 'Full Name' },
];
const [searchBy, setSearchBy] = useState(columns[0].key);
const [searchValue, setSearchValue] = useState('');
async function fetchData(searchBy, value) {
const sort = `$sort[${orderBy}]`;
let params = {
$limit: 50,
$skip: 0,
[sort]: 1
};
if (searchBy && value) {
const search = `${searchBy}[$like]`;
params = { ...params, [search]: '%' + value + '%', };
}
setLoading(true);
const response = await getTableData(params); // api call which is from another file
if (response.status >= 400) {
sessionStorage.clear();
window.location.reload(false);
} else {
const dataList = disablePagination ? _.get(response, 'data') : _.get(response, 'data.data');
setTotal(_.get(response, 'data.total'));
setData(disablePagination ? dataList : addColumn(dataList));
setLoading(false);
}
}
const search = async () => {
globalSearchValue = searchValue;
globalSearchID = searchBy
fetchData(searchBy, searchValue);
}
return(
<Box display="flex" flexDirection="row" alignItems="center">
<FormControl style={{ width: 200, marginRight: 3 }}>
<BootstrapInput
placeholder='Search'
value={searchValue}
onChange={(event) => setSearchValue(event.target.value)}
/>
</FormControl>
<FormControl style={{ width: 200 }}>
<Select
value={searchBy}
onChange={(event) => setSearchBy(event.target.value)}
input={<BootstrapInput />}
>
{searchableColumns ?
searchableColumns.map(columns => <MenuItem key={columns.label} value={columns.key}>{columns.label}</MenuItem>)
: columns.map(columns => <MenuItem key={columns.label} value={columns.key}>{columns.label}</MenuItem>)}
</Select>
</FormControl>
<Tooltip title="Search" style={{ marginLeft: 5, marginRight: 30 }}>
<SearchIcon aria-label="Search" onClick={() => {search()}} />
</Tooltip>
</Box>
)
}
Api.js
getAPI = path => params => {
const body = {
method: 'GET',
url: this.baseUrl + path,
params
}
return this.axios(body).then(response => {
return Promise.resolve(response);
}).catch(error => {
if (error.response) {
return Promise.resolve(error.response);
}
else {
}
return Promise.resolve(error);
});
};
...
getTableData = this.getAPI('/users');
当我发现很难再添加1个过滤器时,该如何处理?
我需要参与后端代码吗?
请让我知道是否需要更多详细信息。