[英]How to access the props in react component?
import React, { Component } from 'react';
class newsList extends React.Component {
render(){
return(
<div>
{JSON.stringify(this.props.arr)}
</div>
)
}
}
export default newsList;
在上面的代碼中, arr
是一個來自另一個組件的對象。 我可以使用JSON.stringify(this.props.arr.result)
顯示數據。 但是,一旦我使用JSON.stringify(this.props.arr.result.id)
對其進行更改, JSON.stringify(this.props.arr.result.id)
收到一個錯誤消息TypeError: this.props.arr.result is undefined
。 我不明白我在做什么錯?
我幾乎肯定地說,在某個時間點,您的this.props.arr
是undefined
,但最終會被分配一個值。 您的初始渲染將收到null
或undefined
,但是如果您嘗試進一步執行不存在的鍵,則會引發該錯誤。 您可以使用布爾值來控制最初呈現的內容。
代替以下代碼:
{JSON.stringify(this.props.arr)}
嘗試這個:
{this.props.arr ? JSON.stringify(this.props.arr) : null}
編輯:這是this.props.arr.result.id
的問題嗎? 如果是這樣,請改用它
{this.props.arr.result ? JSON.stringify(this.props.arr.result.id) : null}
嘗試以下代碼:
class NewsList extends React.Component {
constructor(props) {
super(props);
this.props = props;
}
render() {
return <div>{this.props.arr}</div>;
}
}
React.Component
的constructor
始終將props
作為其第一個參數。
是this.props.arr
數組嗎? 如果是,則render函數應為
render(){
var ids = this.props.arr.map(e=>(<div>e.result.id</div>))
return(
<div>
{ids}
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.