首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React框架。对象解构不起作用

React框架。对象解构不起作用
EN

Stack Overflow用户
提问于 2020-09-17 14:09:16
回答 2查看 177关注 0票数 0

我有一个主页,其中有3张卡片显示。当点击特定的卡片时,图像就会显示出来。现在我可以更改路线,但我不能显示图像和方向。因为它所说的都是解构未定义的。不过,控制台日志显示的是JSON数据。

`

代码语言:javascript
复制
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import DetailsOfDestination from '../DetailsOfDestination/DetailsOfDestination';
import FakeData from '../Fakedata/FakeData';

const PlaceDetail = (props) => {
    const [info, setInfo] = useState(FakeData);
    const {heading, img, text} = props.place
    return (
        <div>
             {
               info.map(singleInfo => <DetailsOfDestination singleInfo={singleInfo}></DetailsOfDestination>)
             }
           <Link to={`/DetailsOfDestination`}>
                <img src={img} alt=""/>
           </Link>
        </div>
    );
};

export default PlaceDetail;

`

代码语言:javascript
复制
import React from 'react';

const DetailsOfDestination = (props) => {
    console.log(props.singleInfo);
    const {heading, img} = props.singleInfo;
    //console.log(heading);
    return (
        <div>
            <h1>{heading}</h1>
        </div>
    );
};

export default DetailsOfDestination;

代码语言:javascript
复制
const data = [
{
    img:'https://i.ibb.co/pxgYz0b/Group-1333.png',
    heading: 'Cox Bazar',
    text: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s,'
},
{
    img:'https://i.ibb.co/3dLyGVd/Group-1335.png',
    heading: 'Sreemangal',
    text: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s,'
},
{
    img:'https://i.ibb.co/qkHmMFD/Group-1337.png',
    heading: 'Sundarban',
    text: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s,'
}

]

导出默认数据;

EN

回答 2

Stack Overflow用户

发布于 2020-09-17 14:24:54

看不到数据--很难说,但我猜标题和img是通过道具传递的singleInfo对象的属性。

如果你不解构父对象-你将无法访问它的子对象-所以singleInfo是变量,而标题和img是该对象的属性-所以你需要稍微改变一下解构的语法。

这样做既可以访问singleInfo非结构化对象,也可以按照指定的方式为其子对象设置别名。

代码语言:javascript
复制
const { singleInfo , singleInfo: { heading , img} } = props;
票数 1
EN

Stack Overflow用户

发布于 2020-09-17 14:26:22

如果您确定FakeData中存在标题,则可以使用解构,也可以像这样使用

代码语言:javascript
复制
<div>
 { props.singleInfo.heading ? (<h1>{props.singleInfo.heading}</h1>) : null }
</div>

PS:我注意到解构需要修改。

代码语言:javascript
复制
const {heading, img } = {...props.singleInfo}

请参考演示:Demo

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63932193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档