繁体   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