簡體   English   中英

如何從對象數組中獲取值?

[英]How to get value from array of objects?

我有一個反應應用程序,並使用 redux 和 props 將對象數組放入我的組件中,我正在獲取它們。 但是我無法訪問該數組中的一個對象內的特定屬性。

有了這個:

console.log(this.props.users)

在此處輸入圖片說明 我得到了包含所有對象的列表數組。 但是當我需要訪問該對象的特定對象或屬性時,例如:

console.log(this.props.users[0])
console.log(this.props.users[0].name)

我收到錯誤:

Cannot read property '0' of undefined

但是當我使用 map() 方法遍歷數組時,我可以訪問它,它可以工作。 為什么我不能正常訪問?

可能是當您執行該行時this.props.users未定義。 檢查您添加console.log(this.props.users[0])的流程

您正在嘗試在加載之前訪問this.props.users屬性。 您的組件無需等待數據獲取即可呈現。 當你console.log(this.props.users)你說你得到一個數組,但在此之上,當組件在this.props.users加載之前呈現時,它可能至少記錄一次undefined

你有幾個選擇。 您可以在渲染方法的最頂部執行此操作,以防止方法中的其余代碼執行:

if (!this.props.users) return null;

一旦數據被獲取並且 props 改變,render 方法將被再次調用。

另一個選項是為減速器中的users聲明一個空數組的默認值。

const App = () => {
  
  const example = () => {
    const data =[{id:1 ,name: "Users1", description: "desc1"}, 
                {id:2 ,name: "Users2", description: "desc2"}];
    return (
      <div>
      {data.map(function(cValue, idx){
          console.log("currentValue.id:",cValue.id);
          console.log("currentValue.name:",cValue.name);
          console.log("currentValue.description:",cValue.description);
         return (<li key={idx}>name = {cValue.name} description = {cValue.description}</li>)
      })}
      </div>
      );
    }

  return(
    <p style = {{color:'white'}}>
      {example()}
    </p>
  );
}

export default App;

暫無
暫無

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

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