英文:
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: 'doctor',
car: 'Honda',
age: 45,
}
But I got this
{
age: 45,
car: 'Honda',
profession: 'doctor',
}
React Component
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>
);
}
Maybe you know, where am I wrong?
答案1
得分: 1
依赖对象属性顺序不被建议(请参阅此答案以了解更多信息)。如果您希望以特定方式显示数据,您可以:
- 使用按顺序排列的对象属性(即
data.age
) - 从您的后端返回属性数组(即
[{ 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
- use the object properties in ordered columns (ie
data.age
) - return an array of properties from your backend (ie
[{ age: 45 }, { car: 'honda' }, ...
There are other options, but these are the most direct and deterministic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论