简体   繁体   中英

props destructuring in react

I have component props looks like

**props**
{
  banner : {
    logo: "...",
    banner: "..."
  },
  content, 
  ...
} 


I grab this props like this

const MyComponent = (props) => {
  const { 
    banner: { logo, title },
    content
  } = props; 
  ... 
  function someFunction(){
    if( banner.logo) {. // <- banner is undefined
      if(title) // <- this title works 
    }
   ... 
  }
  ... 
}

I tried to destructuring props object and use all of these banner, content, logo, title

but compiler complains banner as undefined. Am I doing wrong about destructuring?

When you are destructuring objects like the following, only logo , title and content are unpacked.

  const { 
    banner: { logo, title },
    content
  } = props; 

That's why inside someFunction in your question, you could just do:

function someFunction() {
  if (logo) {
  ...
    if (title) {
    ...
    }
  }
}

If you also want to use the variable banner , you have to do the following:

const { banner, content } = props;
const { logo, title } = banner;

Read more about Destructuring assignment

Simple, you are not taking the banner variable from the props actually, you are taking title and logo instead.

You can do this:

const MyComponent = (props) => {
  const { 
    banner,
    content
  } = props; 
  ... 
  function someFunction(){
    if( banner.logo) {
      if(banner.title)
    }
   ... 
  }
  ... 
}

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