Axios意外地按字母顺序排序响应数据。

huangapple go评论74阅读模式
英文:

Axios accidentelly sort response data alphabetically

问题

我在React中很新,需要显示来自axios响应的数据。应该按照数据库中的顺序,但奇怪的是axios按字母顺序对我的数据进行了排序。我检查了后端返回的数据,一切都正常。
例如,原始数据是:

{
  profession: 'doctor',
  car: 'Honda',
  age: 45,
}

但我得到了这个:

{
  age: 45,
  car: 'Honda',
  profession: 'doctor',
}

React组件:

function SearchForm({ reqForms }) {
  const { register, handleSubmit } = useForm();
  const fetchForms = async (data) => {
    const res = await axios.post("/api/v1/forms/filtered", data)
    console.log(res)
  };
  return (
    <form onSubmit={handleSubmit(fetchForms)} className={styles.searchBar}>
      <input 
        type="text" 
        {...register("profession")} 
      />
      <button>Search</button>
    </form>
  );
}

也许你知道我错在哪里?

英文:

I'm very new in React and I need to display data from axios response. It should be in order that is in db, but strangely axios sort my data alphabetically. I check my backend returning data and it's normal.
For example original data is:

{
  profession: &#39;doctor&#39;,
  car: &#39;Honda&#39;,
  age: 45,
}

But I got this

{
  age: 45,
  car: &#39;Honda&#39;,
  profession: &#39;doctor&#39;,
}

React Component

function SearchForm({reqForms}) {
  const { register, handleSubmit } = useForm();
  const fetchForms = async (data) =&gt; {
    const res = await axios.post(&quot;/api/v1/forms/filtered&quot;, data)
    console.log(res)
  };
  return (
    &lt;form onSubmit={handleSubmit(fetchForms)} className={styles.searchBar}&gt;
      &lt;input 
        type=&quot;text&quot; 
        {...register(&quot;profession&quot;)} 
      /&gt;
      &lt;button&gt;Search&lt;/button&gt;
    &lt;/form&gt;
  );
}

Maybe you know, where am I wrong?

答案1

得分: 1

依赖对象属性顺序不被建议(请参阅此答案以了解更多信息)。如果您希望以特定方式显示数据,您可以:

  1. 使用按顺序排列的对象属性(即 data.age
  2. 从您的后端返回属性数组(即 [{ age: 45 }, { car: 'honda' }, ...

还有其他选项,但这些是最直接和确定性的。

英文:

Relying on object property order is not advised (see this answer for more on this). If you wish to have the data displayed in a certain way, you can

  1. use the object properties in ordered columns (ie data.age)
  2. return an array of properties from your backend (ie [{ age: 45 }, { car: &#39;honda&#39; }, ...

There are other options, but these are the most direct and deterministic.

huangapple
  • 本文由 发表于 2023年6月30日 03:32:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定