簡體   English   中英

console.log 顯示數據但在 if 條件 javascript 中出錯(使用內部反應組件)

[英]console.log showing data but getting error in if condition javascript (using inside react component)

我是 Javascript 的新手,我正在嘗試在下面的 React 容器組件內調用 onClick 事件的代碼是我的代碼

  const onClickHandler = (e) => {
    if (e != null){
      const row_id = e.target.getAttribute('key');
      var cur_row;
      if (api_data != undefined || api_data != null){
      for (cur_row=0; api_data.length-1; cur_row++){
        console.log('this is api data', api_data[cur_row]['id'])
        if (api_data[cur_row]['id'] == row_id){
          console.log(api_data[cur_row])
          break
        }
      }}
  }}

在上面的代碼中,api_data 是我存儲數據的 hookstate 變量。 在控制台日志中,我能夠看到數據,但是當涉及到 console.log 語句正下方的 if 條件時,我收到錯誤消息“無法讀取未定義的屬性‘id’”。 我搜索了一些類似的問題,但無法理解誰來解決我的問題。 知道我錯過了什么

const onClickHandler = (e) => {
    if (e != null){
      const row_id = e.target.getAttribute('key');
      var cur_row;
      if (api_data != undefined || api_data != null){
/* 
I guess you forgot to add exit statement in for loop, 
because of it curr_row value was increasing way beyond 
api_data.length giving you undefined output and hence that error
*/
      for (cur_row=0; curr_row <= api_data.length-1; cur_row++){
        console.log('this is api data', api_data[cur_row]['id'])
        if (api_data[cur_row]['id'] == row_id){
          console.log(api_data[cur_row])
          break
        }
      }}
  }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM