简体   繁体   中英

Prop is undefined when passed to functional component in react

I am trying to include PrintGrid functional component in my LoadGridData component. The PrintGrid should receive a document_id of firebase from LoadGridData. 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.

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.

{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 && <p> {grid_data[0]} </p>}

You are not passing the props object and just passing grid_id direct to PrintGrind function

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.

You could also just do PrintGrid(props) and inside the function access props.grid_id

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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