如何实现此URL中所示的括号?

{{url}}/invoices?orderBy[created_at]=asc&orderBy[reference_number]=asc

screenshot from Postman showing URL format

invoiceApi.js

import api from '@/api/api';
import { useMutation, useQuery } from '@tanstack/react-query';

const invoiceUrl = `/invoices`;

export const fetchInvoices = (
  {
    pageNumber,
    pageSize,
    search = '',
    orderBy = { created_at: 'asc', reference_number: 'asc' },
  },
  config
) => {
  const params = {
    page: pageNumber + 1,
    size: pageSize,
    search,
    orderBy, // 👈 no spread syntax here
  };
  return api.get(invoiceUrl, {
    ...config,
    params: {
      ...config.params,
      ...params,
    },
  });
};

export const useFetchInvoicesQuery = (data) => {
  const { pageNumber, pageSize, search } = data;
  return useQuery({
    queryKey: ['invoices', pageNumber, pageSize, search],
    queryFn: () => fetchInvoices(data),
  });
};

InvoiceAutocomplete.js

import { useFetchInvoicesQuery } from '@/api/invoiceApi';
import { useDebounceValue } from '@/hooks/useDebounceValue';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import PropTypes from 'prop-types';
import React, { useState } from 'react';

export default function renderInvoiceAutocomplete(params) {
  return <InvoiceAutocomplete {...params} />;
}

const InvoiceAutocomplete = ({
  field,
  form: { touched, errors, setFieldValue },
  ...props
}) => {
  const [inputValue, setInputValue] = useState('');
  const debouncedInputValue = useDebounceValue(inputValue, 500);

  const { data: response, isLoading } = useFetchInvoicesQuery({
    pageNumber: 0,
    pageSize: 50,
    search: debouncedInputValue,
  });

  const handleChange = (_, newValue, reason) => {
    if (reason === 'clear') {
      setFieldValue(field.name, { id: '', invoice_number: '' });
      setFieldValue('total_amount', undefined);
      return;
    }
    setFieldValue(field.name, newValue);
    setFieldValue('total_amount', newValue?.amount);
  };

  const handleInputChange = (_, newInputValue) => {
    setInputValue(newInputValue);
  };

  return (
    <Autocomplete
      {...field}
      getOptionLabel={(option) =>
        typeof option === 'string' ? option : option?.invoice_number || ''
      }
      renderOption={(props, option) => {
        return (
          <li {...props} key={option.id}>
            {option?.invoice_number}
          </li>
        );
      }}
      filterOptions={(x) => x}
      options={response?.data?.data || []}
      autoComplete
      includeInputInList
      filterSelectedOptions
      noOptionsText={isLoading ? 'Loading...' : 'No data'}
      onChange={handleChange}
      inputValue={inputValue}
      onInputChange={handleInputChange}
      renderInput={(params) => (
        <TextField
          {...params}
          {...props}
          error={touched[field.name] && errors[field.name] ? true : false}
          helperText={
            touched[field.name] &&
            errors[field.name] &&
            String(errors[field.name].id)
          }
        />
      )}
      fullWidth
    />
  );
};

InvoiceAutocomplete.propTypes = {
  field: PropTypes.object.isRequired,
  form: PropTypes.object.isRequired,
};

推荐答案

Axios具有专门处理此用例的功能.

通过params选项传递查询参数数据,它将自动转换对象以使用方括号表示法.

const invoiceUrl = 'https://echo.zuplo.io/'; // just for the demo
const api = axios.create();

const fetchInvoices = (
  {
    pageNumber,
    pageSize,
    search = '',
    orderBy = { created_at: 'asc', reference_number: 'asc' },
  },
  config = {},
) => {
  const params = {
    page: pageNumber + 1,
    size: pageSize,
    search,
    orderBy, // 👈 no spread syntax here
  };
  return api.get(invoiceUrl, {
    ...config,
    params: {
      ...config.params,
      ...params,
    },
  });
};

fetchInvoices({
  pageNumber: 1,
  pageSize: 10,
}).then(({ data }) => {
  console.log(data.url);
});
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Javascript相关问答推荐

是什么原因导致此Angular 16电影应用程序中因类型错误而不存在属性?

我应该在redux reducer中调用其他reducer函数吗?

vscode扩展-webView Panel按钮不起任何作用

从mat—country—select获取整个Country数组

Javascript,部分重排序数组

无法访问Vue 3深度监视器中对象数组的特定对象值'

如何在ASP.NET JavaScript中使用Google Charts API仅对绘制为负方向的条形图移动堆叠条形图标签位置

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

在Java中寻找三次Bezier曲线上的点及其Angular

如何发送从REST Api收到的PNG数据响应

如何在.NET Core中将chtml文件链接到Java脚本文件?

为什么我的按钮没有从&q;1更改为&q;X&q;?

如何在Java脚本中对列表中的特定元素进行排序?

如何访问此数组中的值?

背景动画让网站摇摇欲坠

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

如何动态呈现适合未知屏幕大小的最大数量的表行?苗条的

与find()方法一起使用时,Mongoose中的$or运算符没有提供所有必需的数据

使用导航时,路径的所有子组件都必须是路径

如何让noWrap在嵌套在Alert/AlertTitle组件中的排版组件中工作?