[英]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.