代码之家  ›  专栏  ›  技术社区  ›  merko

React道具解构返回未定义

  •  1
  • merko  · 技术社区  · 7 年前

    我对解构道具有一个问题,当我不解构道具时它会被定义,但当我解构道具时它是空的。。

     const { navigation, book } = this.props; 
     {console.log('book: '+JSON.stringify(book))}
    

    当我想像这样访问对象时,它会用其中的volumeInfo对象来控制对象:

     const { navigation, book: { volumeInfo: { title, description }} } = this.props; 
     {console.log(title, description)}
    

    那么它就不会了,它的道具。卷信息。标题为空 用title&&安慰日志(标题)但什么都没有。。。

    以下是第一个案例的控制台日志:

     book: {"kind":"books#volume","id":"__JIDwAAQBAJ","etag":"6y5RWEIbrcY","selfLink":"https://www.googleapis.com/books/v1/volumes/__JIDwAAQBAJ","volumeInfo":{"title":"Make Me","authors":["Kaye Blue"],"publisher":"Kaye Blue","description":"<p><b><i>They might make a great team … if they don’t kill each other first.</i></b></p><p>Cree Manning loves everything about being an attorney…except her colleague, Aaron. He may be an actual prince, but he’s also used to coasting through life on his good looks and status. Aaron's hot enough to melt ice, but his arrogance and more than questionable work ethic drive her up a wall.</p><p>His Royal Highness, Aaron Sarda, is third in line to the throne…which means his role in the Kingdom of Medina is mostly ornamental. He hates feeling useless, and working with Cree has taught him that he hates being looked down on even more. Sure, she’s gorgeous, but she’s also rigid, overbearing, and utterly immune to his charm.</
    2 回复  |  直到 7 年前
        1
  •  1
  •   Daniel Daza    7 年前

    试试这个

     const { navigation } = this.props; 
     const { title, description } = this.props.book.volumeInfo;
     {console.log(title, description)}
    
        2
  •  0
  •   RIYAJ KHAN    7 年前

    destructuring assignment ,在赋值的左侧,它定义了要从源变量中解包的值。

    所以,在这个赋值场景中,它不是 volumeInfo .

    这就是syntaxt错误的原因。 未捕获引用错误:未定义volumeInfo .

    如果你想访问 title 通过 卷信息 那就这样做吧。

    var { book:  volumeInfo } = props; 
    

    var { book:  {volumeInfo }} = props;
    

    就你而言,

    var { book: { volumeInfo: { title, description }} } = props;
    

    title & description 将直接正确打印值,但不能通过 卷信息

    推荐文章