Javascript 为什么当我在React中使用props.element时它会变得未定义?
我有一个我发送到的React元素Javascript 为什么当我在React中使用props.element时它会变得未定义?,javascript,html,reactjs,react-props,Javascript,Html,Reactjs,React Props,我有一个我发送到的React元素 <Element first={this.props.first} list1={this.state.list1} list2={this.state.list2} /> 这里的输出是: 某物 然后 未捕获的TypeError:无法读取未定义的属性“dead” 但是如果我不使用list2的值,那么它会在日志记录中打印正确的列表。我的意思是,对于这样的代码,记录的数据是正确的且非空的: const Element = (props) => (
<Element first={this.props.first} list1={this.state.list1} list2={this.state.list2} />
这里的输出是:
某物
然后
未捕获的TypeError:无法读取未定义的属性“dead”
但是如果我不使用list2
的值,那么它会在日志记录中打印正确的列表。我的意思是,对于这样的代码,记录的数据是正确的且非空的:
const Element = (props) => (
<div className='a'>
{console.log('something' + JSON.stringify(props.list2))}
<Link className='class' to={true ? ('/abc/' + (props.first.a ? props.first.a : '')) : ''}>
{props.first.a ? <i>{props.first.b}</i> : 'Do'}
</Link>
</div>
)
const元素=(道具)=>(
{console.log('something'+JSON.stringify(props.list2))}
{props.first.a?{props.first.b}:'Do'}
)
这里的输出是:
某物[{“姓名”:“a”,“死亡”:真},{“姓名”:“b”,“死亡”:假}]
props.first.name的输出为:
“a”
我不明白为什么会这样。非常感谢您的帮助。很可能,第一次呈现
元素时,props.list2
是空的(或者至少不包含与props.exam.id
匹配的内容),但随后父组件会使用一个非emtpty列表/具有匹配项的列表重新呈现它。您的代码在尝试使用其dead
属性之前没有检查props.list2.find
是否找到了某个内容,如果find
没有找到任何内容(例如,因为列表为空),则该属性将爆炸。web控制台中关于尝试使用undefined
的属性dead
时应出现错误find
如果没有找到任何内容,则返回undefined
您需要:
更新元素
中的逻辑,以允许道具列表2.find
不会找到任何东西;或
更新父元素,使其不使用列表呈现element
,其中props.list2.find
将找不到任何内容(但这需要进行重构,以便父元素将您要查找的内容传递到element
,而不是让element
尝试查找它)
请使用演示问题的工具更新您的问题,最好是使用堆栈片段([]
工具栏按钮)运行的工具。堆栈代码段支持React,包括JSX。(请不要仅对不可运行的代码块使用堆栈片段。请使用代码块。)我已使用模拟数据进行了检查,其中包含我要查找的数据。find
应该可以工作。问题是,当我不使用find
打印数据时,它不工作并显示空列表,但当我不使用find
时,它会显示正确的非空列表。我已经为添加了控制台日志数据help@Panda-但是,当find
没有找到任何内容时,会出现错误。因此,很明显,组件至少被调用一次,但列表中没有您要查找的内容(然后很可能再次被调用)。
const Element = (props) => (
<div className='a'>
{console.log('something' + JSON.stringify(props.list2))}
<Link className='class' to={true ? ('/abc/' + (props.first.a ? props.first.a : '')) : ''}>
{props.first.a ? <i>{props.first.b}</i> : 'Do'}
</Link>
</div>
)