[英]How can I iterate through an array of objects, make an API call for each object, then set the response as a value in each object
[英]Need to call an api for each key stroke in react, but the response can have thousands of objects
我在前端使用 react 和 axios,在后端使用帶有 prisma 的 nextjs。 我在數據庫中有 4000 個包含健身練習的練習。 我想創建一個 function,每次擊鍵,api 都會查找相關的練習。 我完成了創建它,但我有一些問題:
主要問題是響應從第一次擊鍵開始延遲,因為負載響應太大。 我創建了一個可滾動的 UL 元素來呈現元素,因為我還想獲得 Gif 圖像。 因此,如果 API 能找到這些元素,它們就會呈現在屏幕上。
如果我向每個元素添加一個點擊事件,到 select 練習的 ID,我會收到錯誤消息“屏幕上重新渲染太多”。
function如何優化,如何解決屏幕上重新渲染太多的錯誤? Nextjs 告訴我它將創建一個無限循環....
前端看起來像這樣:
const [open, setOpen] = useState(false);
const [keyWord, setKeyWord] = useState('');
const [array, setArray] = useState([]);
const [exerciceId, setExerciceId] = useState('');
// Add exercice
const hadnleAddExercie = async event => {
event.preventDefault();
console.log('exercice added');
}
// Look for exercices
const searchExercices = async event => {
event.preventDefault();
setKeyWord(event.target.value);
const arrayExercices = await getExercicesByKeyWords(keyWord);
setArray(arrayExercices);
console.log(arrayExercices);
}
<div className='flex mt-3 flex-col'>
<input onChange={searchExercices} required placeholder='Search by word...' className='border border-slate-400 p-1 rounded-md flex-1 max-w-sm my-2'/>
<ul className='border border-slate-400 p-1 rounded-md max-w-sm my-2 max-h-52 overflow-scroll'>
{
array.length > 1 && array.map(exercice => (
<li key={exercice.id} className='flex flex-wrap p-2 bg-slate-200 m-2 items-center rounded-md'>
<span><Image className='rounded-xl mr-2' priority width={40} height={40} src={exercice.gifUrl} alt={exercice.name}/></span>
<span>{ exercice.name }</span>
</li>
))
}
</ul>
</div>
后端使用 prisma,我使用 OR 子句在不同的行中查找單詞:
export default async function handler(req, res) {
try {
const param = req.query.slug[0];
console.log(param);
// Get exercices where the two rows contains a single parametter
const exercices = await prisma.exercices.findMany({
where: {
OR: [
{
name: {
contains: param
}
},
{
target: {
contains: param
}
},
{
equipment: {
contains: param
}
}
]
}
});
res.status(200).send(exercices);
}
catch (error) {
console.log(error);
res.status(500).send(error);
}
}
只是為了找到一個練習,我使用了 500mb...
以下是我可以想到的幾種優化方法:
React.memo
來防止每次 state 更改時重新呈現列表,只有在實際列表更改時才重新呈現它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.