简体   繁体   English

当传递给反应中的功能组件时,Prop 是未定义的

[英]Prop is undefined when passed to functional component in react

I am trying to include PrintGrid functional component in my LoadGridData component.我正在尝试在 LoadGridData 组件中包含 PrintGrid 功能组件。 The PrintGrid should receive a document_id of firebase from LoadGridData. PrintGrid 应该从 LoadGridData 接收 firebase 的 document_id。 But inside the return statement of the LoadGridData, I try to pass the grid_id which is in a grid_data list to PrintGrid and it causes grid_id value to be undefined.但是在 LoadGridData 的 return 语句中,我尝试将 grid_data 列表中的 grid_id 传递给 PrintGrid,这导致 grid_id 值未定义。

function PrintGrid(grid_id) {
  console.log('Print grid_id in PrintGrid: ', grid_id);

The below gives an error that it cannot access index 0 of undefined.下面给出了一个错误,它无法访问未定义的索引 0。

{grid_data && <PrintGrid grid_id={grid_data[0]} />}

With only the following statement, it updates the grid_data[0] value (grid_id) to the webpage.仅使用以下语句,它将 grid_data[0] 值 (grid_id) 更新到网页。

{grid_data && <p> {grid_data[0]} </p>}

You are not passing the props object and just passing grid_id direct to PrintGrind function您没有传递道具对象,只是将 grid_id 直接传递给 PrintGrind 函数

Change改变

function PrintGrid(grid_id) {

to

function PrintGrid({grid_id}) {  

The above is the ES6 way of de-structuring objects and getting fields within directly.以上是 ES6 解构对象和直接获取字段的方式。

You could also just do PrintGrid(props) and inside the function access props.grid_id你也可以只做 PrintGrid(props) 并在函数内部访问 props.grid_id

function PrintGrid(props) {  
    console.log(props.grid_id)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM