[英]Loop Inside function of React Component
(React web 應用開發)為了檢查產品的當前庫存狀態,我使用產品的 ID 循環遍歷 json 數據。 我正在嘗試通過鍵(id)從 json(下)檢索“DATAPAYLOAD”的值。 idsent 是從另一個組件傳遞的字符串。 但是“if (Data.response[i].id === idsent)”這個條件似乎總是錯誤的,因為我在控制台中“失敗”了。 如果有人可以查看以下代碼並給我一些建議,那將非常有幫助,在此先感謝!
onButtonClicked = () => {
const idsent="D56F36C6038DFC8244F"
for (var i = 0; i < Data.response.length; i++) {
if (Data.response[i].id === idsent) {
name = Data.response[i].DATAPAYLOAD;
const word = '<INSTOCKVALUE>INSTOCK</INSTOCKVALUE>';
if (name.includes(word)) {
return true;
}
else {
return false;
}
}
console.log("failed");
}
以下是通過 fetch get-method 請求的 json 數據的一部分。
Data= {
"code": 200,
"response": [
{
"id": "CED62C6F96BD0E21655142F",
"DATAPAYLOAD": "<AVAILABILITY>\n <CODE>200</CODE>\n
<INSTOCKVALUE>OUTOFSTOCK</INSTOCKVALUE>\n</AVAILABILITY>"
},
{
"id": "D56F36C6038DFC8244F",
"DATAPAYLOAD": "<AVAILABILITY>\n <CODE>200</CODE>\n
<INSTOCKVALUE>LESSTHAN10</INSTOCKVALUE>\n</AVAILABILITY>"
},
{
"id": "4536C9E608B563A749",
"DATAPAYLOAD": "<AVAILABILITY>\n <CODE>200</CODE>\n
<INSTOCKVALUE>INSTOCK</INSTOCKVALUE>\n</AVAILABILITY>"
},
{
"id": "3A576872130625CABFADEE68",
"DATAPAYLOAD": "<AVAILABILITY>\n <CODE>200</CODE>\n
<INSTOCKVALUE>INSTOCK</INSTOCKVALUE>\n</AVAILABILITY>"
}
]
}
再次感謝你。
你可能想要console.log("failed");
在for
循環之外,如下所示(以便它僅在處理完所有數據后執行):
onButtonClicked = () => {
const idsent="D56F36C6038DFC8244F"
for (var i = 0; i < Data.response.length; i++) {
if (Data.response[i].id === idsent) {
name = Data.response[i].DATAPAYLOAD;
const word = '<INSTOCKVALUE>INSTOCK</INSTOCKVALUE>';
if (name.includes(word)) {
return true;
}
else {
return false;
}
}
}
console.log("failed");
獲取成功后,需要使用 json() 讀取並解析數據。 請讀這個
onButtonClicked = async () => {
const idsent="D56F36C6038DFC8244F"
Data = await Data.json(); // json() will create a promise
for (var i = 0; i < Data.response.length; i++) {
if (Data.response[i].id === idsent) {
name = Data.response[i].DATAPAYLOAD;
const word = '<INSTOCKVALUE>INSTOCK</INSTOCKVALUE>';
if (name.includes(word)) {
return true;
}
else {
return false;
}
}
console.log("failed");
}
您失敗的原因是因為第一次通過時,ID 與發送的 ID 不匹配,因此控制台會記錄“失敗”消息。 然后第二次通過 for 循環匹配數據,然后點擊下一個 if,它檢查值。 由於您要搜索的值包含在數據中,因此它返回 true 並退出 for 循環。 您看到失敗日志的原因是因為您在 id 不匹配時進行記錄,並且該數組中有 3 條 id 不匹配的記錄,第一個是其中之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.