首页 > 解决方案 > 反应框架。对象解构不起作用

问题描述

我有一个主页,其中显示了 3 张卡片。单击特定卡时,将显示图像。现在我可以更改路线,但无法显示图像和航向。因为它所说的只是解构未定义。不过,控制台日志显示的是 JSON 数据。

`

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;

`

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;

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,'
}

]

导出默认数据;

在此处输入图像描述

标签: javascriptreactjswebweb-frontendreact-fullstack

解决方案


没有看到数据 - 很难说,但我的猜测是,heading 和 img 是通过 props 传递的 hte singleInfo 对象的属性。

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

这将做的既是 - 授予对 singleInfo 解构对象的访问权限 - 而且还将为其子项指定别名。

const { singleInfo , singleInfo: { heading , img} } = props;

推荐阅读