Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么当我在React中使用props.element时它会变得未定义?_Javascript_Html_Reactjs_React Props - Fatal编程技术网

Javascript 为什么当我在React中使用props.element时它会变得未定义?

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) => (

我有一个我发送到的React元素

<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>
            )