簡體   English   中英

如何訪問React組件中的道具?

[英]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.arrundefined ,但最終會被分配一個值。 您的初始渲染將收到nullundefined ,但是如果您嘗試進一步執行不存在的鍵,則會引發該錯誤。 您可以使用布爾值來控制最初呈現的內容。

代替以下代碼:

{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.Componentconstructor始終將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.

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